PHP Closures - 获取闭包范围起源的类名

案件

我正在玩一个 Laravel 项目,看看是否可以使用闭包来实现排序接口,我注意到当我dd()闭包时,它还显示了将闭包创建为属性的类。


最小化代码

// in my Order model class, i have a function that will return a closure

public static function defaultSortFunction(){

    $sortColumn = property_exists(self::class,'defaultSortingColumn') ? self::$defaultSortingColumn : 'created_at';


    return function($p,$n)use($sortColumn){

        return $p->$sortColumn <=> $n->$sortColumn;

    };

}

// in one of my controller I use for testing, I added these 2 methods for testing

public function index(){

    $sortFunction = Order::defaultSortFunction();

    $this->someOtherFunction($sortFunction);

    return 'done';

}


private function someOtherFunction($fn){

    dd($fn);


    // $scopeModel = get_class($fn); => Closure

    

    // example of how I can use this value later

    // $scopeModel::take(10)->get()->sort($fn);

}

dd()里面的结果someOtherFunction():


^ Closure($p, $n) {#1308 ▼

  class: "App\Order"

  use: {▼

    $sortColumn: "created_at"

  }

}

问题

从结果来看dd(),闭包有一个属性,表明它是在类中定义的App\Order。有什么办法可以访问这个值吗?


我已经尝试过get_class($fn),但正如预期的那样,它给出了"Closure",如果我这样做了$fn->class,它会给出一个错误Closure object cannot have properties。


蓝山帝景
浏览 166回答 2
2回答

鸿蒙传说

您可以在闭包上使用 Reflection API,这是一种比debug_backtrace// in one of my controller I use for testing, I added these 2 methods for testingpublic function index(){&nbsp; &nbsp; $sortFunction = Order::defaultSortFunction();&nbsp; &nbsp; $this->someOtherFunction($sortFunction);&nbsp; &nbsp; return 'done';}private function someOtherFunction($fn){&nbsp; &nbsp; $reflectionClosure = new \ReflectionFunction($fn);&nbsp; &nbsp; dd($reflectionClosure->getClosureScopeClass()->getName());}getClosureScopeClassReflectionClass根据您需要查找的类返回一个实例并getName完成作业。

Cats萌萌

您当然可以通过 defaultSortFunction 中的参数将类名注入到闭包中,但这显然不太好。如果您使用 limit 参数,您应该能够将其限制为仅返回调用类,而不再返回。我不确定,但我怀疑它的性能不是特别好。
打开App,查看更多内容
随时随地看视频慕课网APP