The editor of this article will teach you about the use of inversion of control and dependency injection in PHP. If you are interested, come and take a look!
Inversion of control: control is given to your own class
Dependency injection: dependent on another class, I did not manually new it
<?php /*我自己要用的类*/ class User { private $name; private $age; public function __construct($name,$age){ $this->name=$name; $this->age=$age; } public static function createResource($conf) { return new self($conf['name'],$conf['age']); } public function says(){ echo $this->name; } } $conf=array( 'name'=>'taoshihan', 'age'=>10 ); /*把这个地方放到一个类里,它就是个容器的概念了*/ /*体现了控制反转,所有的操作都是我自己的类里面进行的处理,不需要在调用的时候处理*/ /*这里也体现了依赖注入,就是我不手动去new对象了,我是在下面的方法中获取的对象*/ $user=call_user_func_array(array('User', "createResource"), array($conf)); $user->says();
Related courses: PHP video tutorial
The above is the detailed content of [PHP Learning] Daily use of inversion of control and dependency injection. For more information, please follow other related articles on the PHP Chinese website!