Home>Article>Backend Development> Learn more about dependency injection in PHP and see how to apply it
What is dependency injection? This article will take you to understand dependency injection in PHP, introduce the reasons for dependency injection, and the application of dependency injection. I hope it will be helpful to you!
1. What is Dependency Injection (DI)
II , The reason why dependency injection appears
adapter = new adapter(); } }
3. Simple dependencies Injection
adapter = $adapter; } }
instance[$name] = $value; } } $container = new container(); $container->adapter = new adapter();
5. Application of Dependency Injection
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); //我是调度器
6. High-level optimization
In the above application, we directly inject the instantiated objects into the container.adapter = new adapter(); //高阶优化 $container = new container(); $container->adapter = function () { return new adapter(); };
Recommended learning: "PHP Video Tutorial
The above is the detailed content of Learn more about dependency injection in PHP and see how to apply it. For more information, please follow other related articles on the PHP Chinese website!