Laravel in the construction method of the class is dependent on the injection __construct (User $user) and then the following methods are directly used $this->user call, with the direct use of user::find () What is the difference? What kind of comparison is recommended?
Reply content:
Laravel in the construction method of the class is dependent on the injection __construct (User $user) and then the following methods are directly used $this->user call, with the direct use of user::find () What is the difference? What kind of comparison is recommended?
This is the difference between the static and dynamic methods of the PHP class.
Static methods do not require class instantiation to be used directly class::function
, but must have keywords at the time of declaration static
.
The dynamic method must be instantiated through the class to invoke.
$class= new Class;$class->somefunc();
The two methods are not superior or inferior, the key to see the scene.
In general, a static method is recommended if it is not closely related to logic. Because dynamic methods actually need to implicitly pass in a parameter: $this
It has a slight effect on performance.
Does not understand PHP, but in the "dependency interface, rather than rely on the implementation" in the field of programming is a basic idea.
But the interface is not the actual object, how to invoke it, which needs to be injected, we can put all the injected into a place physically. So when you want to modify the implementation of a class, just modify a place.
Class A{ function __construct(User $user){ }}Class B{ function __construct(){ $user = User::find(['id'=>1]); }}$user = User::find(['id'=>1]);$a = new A($user);$b = new B();
If you have business changes in the future, use
Gooduser extends User {}
Code needs to be changed
Class B{ function __construct(){ $user = GoodUser::find(['id'=>1]); }}$user = GoodUser::find(['id'=>1]);$a = new A($user);$b = new B();
There is no discovery that Class B has been changed.!!!
It violates the principle of open closure.
It's like this ~ hehe