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

Hel*_*rch 4 php closures laravel

案件

\n

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

\n

最小化代码

\n
// in my Order model class, i have a function that will return a closure\npublic static function defaultSortFunction(){\n    $sortColumn = property_exists(self::class,'defaultSortingColumn') ? self::$defaultSortingColumn : 'created_at';\n\n    return function($p,$n)use($sortColumn){\n        return $p->$sortColumn <=> $n->$sortColumn;\n    };\n}\n
Run Code Online (Sandbox Code Playgroud)\n
// in one of my controller I use for testing, I added these 2 methods for testing\npublic function index(){\n    $sortFunction = Order::defaultSortFunction();\n    $this->someOtherFunction($sortFunction);\n    return 'done';\n}\n\nprivate function someOtherFunction($fn){\n    dd($fn);\n\n    // $scopeModel = get_class($fn); => Closure\n    \n    // example of how I can use this value later\n    // $scopeModel::take(10)->get()->sort($fn);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

dd()里面的结果someOtherFunction()

\n
^ Closure($p, $n) {#1308 \xe2\x96\xbc\n  class: "App\\Order"\n  use: {\xe2\x96\xbc\n    $sortColumn: "created_at"\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

问题

\n

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

\n

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

\n

Shi*_*n83 7

您可以在闭包上使用 Reflection API,这是一种比debug_backtrace

// 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){
    $reflectionClosure = new \ReflectionFunction($fn);
    dd($reflectionClosure->getClosureScopeClass()->getName());
}
Run Code Online (Sandbox Code Playgroud)

getClosureScopeClassReflectionClass根据您需要查找的类返回一个实例并getName完成作业。

  • 好答案。`$reflectionClosure-&gt;getClosureThis()` 也可用于获取闭包绑定到的实例(内部 `$this`)。 (3认同)