依赖注入
//代码实现控制反转&依赖注入 class SuperMan{ public function __construct($obj){ $obj->call(); } } class Xpower{ public function call (){ echo 111; } } class Ultrabomb { public function call(){ echo 222; } } class Container{ protected $binds; protected $instances; public function bind($abstract,$concreate){ if($concreate instanceof Closure){ $this->binds[$abstract]=$concreate; }else{ $this->instances[$abstract]=$concreate; } } public function make($abstract,$paramters=[]){ if(isset($this->instances[$abstract])){ return $this->instances[$abstract]; } array_unshift($paramters,$this); return call_user_func_array($this->binds[$abstract],$paramters); } } $container = new Container(); $container->bind("superman",function($container,$modelName=null){ return new SuperMan($container->make($modelName)); }); $container->bind(‘xpower‘,function($container){ return new Xpower(); }); $container->bind(‘ultrabomb‘,function($container){ return new Ultrabomb(); }); $superman1 = $container->make(‘superman‘,[‘xpower‘]); $superman2 = $container->make(‘superman‘,[‘ultrabomb‘]);
原文:https://www.cnblogs.com/zh718594493/p/12113135.html