<?phpnamespace app\index\controller;class Demo1{//可以通过字符串/数值用get方法来传值到类方法中public function getName($name = 'MHR'){return 'Hello '.$name;}// 依赖注入// \app\common\Temp $Temp:将会触发依赖注入// 会自动实例化化类,依赖注入就是将对象传入方法的手段public function getMathod(\app\common\Temp $temp){//getMathod中的 `\app\common\Temp $temp` 等价于://$temp = new \app\common\Temp;$temp->setName('MRH');return $temp->getName();}}
//绑定一个类到容器public function bindClass(){// //使用容器(Container)类的set方法,把一个类放到容器中:相当于注册到容器中。// \think\Container::set('temp','\app\common\Temp');// //将容器中的类实例化并取出来使用:实例化时可调用构造器进行初始化// $temp = \think\Container::get('temp',['name'=>'Mahairen']);//使用助手函数,和上面的容器绑定方法作用一样bind('temp','\app\common\Temp');$temp = app('temp',['name'=>'PHP中文网']);return $temp->getName();}
//绑定一个闭包到容器:public function bindClosure(){//使用容器(Container)类的set方法,把一个闭包放到容器中。\think\Container::set('demo',function ($domain){return 'php中文网的域名是:'.$domain;});//将容器中的闭包取出来使用return \think\Container::get('demo',['domain'=>'www.php.cn']);}
Temp类:需要被注入的类
<?phpnamespace app\common;class Temp{private $name;public function __construct($name = 'mhr'){$this->name = $name;}public function setName($name){$this->name = $name;}public function getName(){return '方法是:' .__METHOD__ . '属性是:'. $this->name;}}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号