什麼是依賴注入?這篇文章帶大家了解PHP中的依賴注入,介紹一下依賴注入出現的原因、依賴注入的應用,希望對大家有幫助!
一、什麼是依賴注入 (DI)
二、依賴注入出現的原因
<?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(); };
原文網址:https://juejin.cn/post/7004616671864291359
推薦學習:《PHP影片教學》
以上是深入了解PHP中的依賴注入,看看怎麼應用的詳細內容。更多資訊請關注PHP中文網其他相關文章!