亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

PHP Closures - 獲取閉包范圍起源的類名

PHP Closures - 獲取閉包范圍起源的類名

PHP
藍山帝景 2023-07-08 17:49:39
案件我正在玩一個 Laravel 項目,看看是否可以使用閉包來實現排序接口,我注意到當我dd()閉包時,它還顯示了將閉包創建為屬性的類。最小化代碼// in my Order model class, i have a function that will return a closurepublic 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 testingpublic 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。
查看完整描述

2 回答

?
鴻蒙傳說

TA貢獻1865條經驗 獲得超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());

}

getClosureScopeClassReflectionClass根據您需要查找的類返回一個實例并getName完成作業。


查看完整回答
反對 回復 2023-07-08
?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

您當然可以通過 defaultSortFunction 中的參數將類名注入到閉包中,但這顯然不太好。

如果您使用 limit 參數,您應該能夠將其限制為僅返回調用類,而不再返回。

我不確定,但我懷疑它的性能不是特別好。


查看完整回答
反對 回復 2023-07-08
  • 2 回答
  • 0 關注
  • 195 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號