This article brings you relevant knowledge about PHP, which mainly introduces issues related to dependency injection, including what is dependency injection, the reasons for dependency injection, and the application of dependency injection, etc. Wait, I hope it helps everyone.
Recommended study: "PHP Video Tutorial"
One article to understand PHP dependency injection. Many people will hear the term dependency injection after learning PHP for a period of time, but they have only a little understanding of it. I understand that dependency injection is actually a PHP programming design pattern, although it has not been included in the design pattern. Design patterns exist for the efficiency of programming, and dependency injection certainly does.
The most direct sign is when the parameter data is passed as an object. Strictly speaking, you want to operate another class in another class. There is an interdependence between the two classes. The method of passing parameters is called injection
<?php class container { private $adapter; public function __construct() { $this->adapter = new adapter(); } }
<?php class container { private $adapter; public function __construct(adapter $adapter) { $this->adapter = $adapter; } }
<?php class container { public $instance = []; public function __set($name, $value) { $this->instance[$name] = $value; } } $container = new container(); $container->adapter = new adapter();
<?php class container { public $instance = []; public function __set($name, $value) { $this->instance[$name] = $value; } } class adapter { public $name = '我是调度器'; } $container = new container(); $container->adapter = new adapter(); class autofelix { private $container; public function __construct(container $container) { $this->container = $container; } public function who($class) { return $this->container->instance[$class]->name; } } $autofelix = new autofelix($container); $who = $autofelix->who('adapter'); var_dump($who); //我是调度器
<?php $container = new container(); $container->adapter = new adapter(); //高阶优化 $container = new container(); $container->adapter = function () { return new adapter(); };
The above is the detailed content of PHP dependency injection summary sharing. For more information, please follow other related articles on the PHP Chinese website!