主要功能是记录你实际的调用操作,然后在你需要的地方重新调用。该函数与匿名函数基本相同。临时存储你的调用操作,一般用于链式调用。然后它实际作用于你要操作的对象,这个好像和使用场景是一样的。如果laravel项目使用的是仓库模式,那么对于比较复杂的查询条件,一般有3个操作来设置一个规则,用于特殊的查询添加方式,根据这个规则组装数组,然后需要在里面实现解析传递匿名函数仓库类。写在匿名函数中的查询条件现在可以优化第三个方法,在下面的代码中传入一个CallEcho对象//$callEchointhecontroller=(newCallEcho())->where("username","MaYun")->where("is_boss",1)->first();$fubao=(newUserRepository)->first($callEcho);//仓库类classUserRepository{publicfunctionfirst(CallEcho$callEcho){return$callEcho->调用(新用户());}}看起来类似于匿名函数,但是可以继承CallEcho实现一些接口,继承之后可以对查询条件进行一些操作,比如过滤什么的。使用匿名函数,完全取决于调用者的良心。最重要的是不要传递对象,函数名是什么,对象类上的代码CallEcho{protected$callable=null;publicfunction__construct(){//可调用初始化$this->seed();}protectedfunctionseed(){$this->callable=$this;}公共函数__invoke($obj){返回$obj;}公共函数__call($name,$arguments){$current=$this->callable;/***生成每个__call,只是在可调用对象上包裹一层*/$this->callable=function($obj)use($name,$arguments,$current){returncall_user_func_array($current,[$obj])->{$name}(...$arguments);};返回$这个;}//作用于真实对象publicfunctioninvoke($obj){returncall_user_func_array($this->callable,[$obj]);}}简单并使用classTestCallEcho{protected$called=[];公共函数__call($name,$arguments){$this->called[]=[$name,$arguments];返回$这个;}公共功能ionend(){$this->called[]="end";返回$这个;}publicfunctiongetCalled(){return$this->called;}}functiontestArrayEq($array1,$array2){if(count($array1)!==count($array2)){返回假;}foreach($array1as$index=>$value1){if(!isset($array2[$index])){返回假;}$value2=$array2[$index];if(is_array($value1)&&is_array($value2)){if(!testArrayEq($value1,$value2)){返回假;}else{//继续判断}}else{if($value1!==$value2){returnfalse;}}}returntrue;}functiontestTestArrayEq(){$array1=[1,2];$array2=[1,3];$array3=[1,2,3];assert(testArrayEq($array1,$array2)==false);assert(testArrayEq($array1,$array3)==false);assert(testArrayEq($array1,$array1)==true);}testTestArrayEq();$obj=new\stdClass();$callEcho=newCallEcho();/***************键开始***************//**@varCallEcho$callEcho*/$callEcho=$callEcho->testNumber(1)->testString("myname")->testObj($obj)->testMulti(1,"myname")->testMulti2("1",$obj)->end();/**@varTestCallEcho$testCallEcho*/$testCallEcho=$callEcho->invoke(newTestCallEcho());/***********重点结束****************///和这个基本一样$a=function($obj){$obj->testNumber(1)->testString("myname")->testObj($obj)->testMulti(1,"myname")->testMulti2("1",$obj)->end();};$called=$testCallEcho->getCalled();$eq=testArrayEq($called,[["testNumber",[1]],["testString",["myname"]],["testObj",[$obj]],["testMulti",[1,"myname"]],["testMulti2",["1",$obj]],"end"]);assert($eq);PS灵感来自执行slim3中间件欢迎留言
