依赖注入其实就是相当于注册树
容器呢 就是相当于给当前对象加工了一下 或者说 包装了一下

<?php
namespace app\common;
/**
*
*/
class Temp
{
private $name;
public function __construct($name ='李四')
{
$this->name=$name;
}
function setName($name)
{
$this->name=$name;
}
function getName()
{
return '方法是:'.__METHOD__.',属性是:'.$this->name;
}
//__METHOD__ app\common\Temp::getName
}点击 "运行实例" 按钮查看在线实例
<?php
namespace app\index\controller;
/**
* 容器与依赖注入
*/
class Dome1
{
//http://tp.io/Index.php/index/Dome1/getName/name/李四
public function getName($name='张三')
{
return '你好'.$name;
}
//触发依赖注入
public function getMethod(\app\common\Temp $temp)
{
$temp->setName('王五');
return $temp->getName();
}
//绑定一个类到容器
public function bindClass()
{
//把一个类放到容器中:相当于注册到容器(我觉得是相当于给这个类起了一个名字)
\think\Container::set('temp','\app\common\Temp');
//bind()助手函数=\think\Container::set
$temp = \think\Container::get('temp',['name'=>'娃哈哈哈哈']);
// app()助手函数=\think\Container::get
return $temp->getName();
}
// 绑定一个闭包到容器
public function bindClosure()
{
\think\Container::set('demo',function($domes){
return '名字是'.$domes;
});
$temp = \think\Container::get('demo',['domes'=>'喜洋洋']);
return $temp;
}
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号