今天web建站小编给大家介绍一下关于php
简单的DI
注入方法,下面给大家看一下简单的依赖注入代码和高阶的依赖注入代码?
简单的依赖注入代码
<?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(); $container->autofelix = new autofelix(); ?>
依赖注入的应用
<?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(); }; ?>
标签: php, php入门, php问答, Private, Public
上面是“php简单介绍DI注入方法”的全面内容,想了解更多关于 php入门 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_2312.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!