簡體   English   中英

將類變量分配給函數並調用

[英]Assign class variable to function and call

尋找將函數分配給類變量然后調用它的方法。

我知道您可以將var類分配給另一個變量,然后調用它,但是我正在尋找一種無需創建臨時變量也不會使我的代碼混亂的調用方法。

臨時變量或使用call_user_func()我唯一的選擇嗎?

class MyClass {
    public $callMe;
    public function __construct() {
        $this->callMe = function(...$args) {
            print_r(['HIT', $args]);
        };

        // $this->callMe('asd', 'sda');
        // Error: PHP Fatal error:  Call to undefined method test::callMe()

        // This works, but I would prefer not to create temporary variables for this
        $tmp = $this->callMe;
        $tmp('sd','adsf','fdas');
    }
}

請嘗試以下方法之一:

($this->callMe)('sd','adsf','fdas');
call_user_func($this-callMe, 'sd','adsf','fdas');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM