马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
代码实例:
[PHP] 纯文本查看 复制代码
// 轮胎类
class Tyre{
public function roll()
{
echo "轮胎 滚动 <br />";
}
}
// 汽车类
class Car{
protected $tyre;
public function __construct($tyre)
{
$this->tyre = $tyre;
}
// 汽车启动
public function run()
{
$this->tyre->roll();
echo "汽车 启动 <br />";
}
}
class Container{
// 存放所绑定的类 可以绑定多个类
static $register = [];
/**
* todo 将目标对象保存到容器内部
* @param $name
* @param \Closure $closure 回调函数 返回生成对象的方法 使用函数形式存储
* 调用make的时候 当前类中的register中的值是个函数,而不是对象资源,只有在调用的时候,才会生成对象资源
*/
static function bind($name, \Closure $closure){
static::$register[$name] = $closure;
}
/**
* todo 返回所需对象
* 执行register中的方法 返回所需类
* @param $name string 需要用到的类
* @return mixed 返回所需对象
*/
static function make($name){
$closure = static::$register[$name];
// 如果不存在该类
if(!isset($closure)){
return new class{};
}
return ($closure)();
}
/**
* todo 返回容器中绑定的类大小
* @return int
*/
static function getRegSize(){
return count(static::$register);
}
/**
* todo 返回容器中所有类名
* @return array 容器内所有的对象名
*/
static function getRegContent(){
$name = [];
foreach (static::$register as $key=>$closure){
array_push($name, $key);
}
return $name;
}
}
// 绑定轮胎
Container::bind('tyre', function (){
return new Tyre();
});
// 绑定汽车
Container::bind('car', function () {
return new Car(Container::make('tyre'));
});
// 启动汽车
$Car = Container::make('car');
$Car->run();
// 容器对象数量
dump(Container::getRegSize());
// 容器对象类
dump(Container::getRegContent());
结果:
|