废话不说直接上实例

//laravelIOC理解以及依赖注入DIinterfaceSuperModuleInterface{/***超能力激活方法**任何一个超能力都得有该方法,并拥有一个参数*@paramarray$target针对目标,可以是一个或多个,自己或他人*/publicfunctionactivate(array$target);}classXPowerimplementsSuperModuleInterface{publicfunctionactivate(array$target){//这只是个例子。。具体自行脑补}}/***终极×××(就这么俗)*/classUltraBombimplementsSuperModuleInterface{publicfunctionactivate(array$target){//这只是个例子。。具体自行脑补}}classSuperman{protected$module;publicfunction__construct(SuperModuleInterface$module){$this->module=$module;}}classContainer{public$binds;public$instances;publicfunctionbind($abstract,$concrete){if($concreteinstanceofClosure){$this->binds[$abstract]=$concrete;}else{$this->instances[$abstract]=$concrete;}}publicfunctionmake($abstract,$parameters=[]){if(isset($this->instances[$abstract])){return$this->instances[$abstract];}array_unshift($parameters,$this);returncall_user_func_array($this->binds[$abstract],$parameters);}}//创建一个容器(后面称作超级工厂)$container=newContainer;//向该超级工厂添加超人的生产脚本$container->bind('superman',function($container,$moduleName){returnnewSuperman($container->make($moduleName));});//向该超级工厂添加超能力模组的生产脚本$container->bind('xpower',function($container){returnnewXPower;});//同上$container->bind('ultrabomb',function($container){returnnewUltraBomb;});//******************华丽丽的分割线**********************//开始启动生产$superman_1=$container->make('superman',['xpower']);var_dump($container->binds);die;$superman_2=$container->make('superman',['ultrabomb']);$superman_3=$container->make('superman',['xpower']);var_dump($superman_1);die;//...随意添加

laravel核心就是服务容器.所有的服务提供者绑定到容器中.细致的讲解可以取作者的官网进行查看 整个IOC的核心应该是make方法的call_user_func_array()函数的调用

$container->bind('superman',function($container,$moduleName){returnnewSuperman($container->make($moduleName));});

闭包函数

function($container,$moduleName){returnnewSuperman($container->make($moduleName));}

恰好给call_user_fun_array()的第一个参数使用. 执行完三次bind之后,$container->bind中有了三个key->value的 闭包 当再次执行$container->make('superman',['xpower'])时,$container->binds中superman对应上述代码的闭包,参数为[$container,xpower] 执行 new Superman($container->make($moduleName))时,对应$container->make('xpower');则再次走call_user_func_array()的流程,return new xpower()给Superman的construst. 所以IOC实质就是2次调用call_user_func_array();

注:该代码引用自https://www.insp.top/article/learn-laravel-container