簡體   English   中英

將類方法傳遞給PHP中的閉包(類似於JS)

[英]Pass class method to a closure in PHP (similar to JS)

在Javascript中,您可以執行以下操作:

// Define a function
function logIt(a, b) { console.log(a, b); }

function somethingElse() {
    // Store it in a variable
    var theLog = logIt; 
    // Call it somewhere else *as the variable-name*
    asyncCall(function() { theLog(1, 2); });
}

我想在PHP中做的是這樣的:

class A
{
    // Define a simple class method
    protected function echoIt($a, $b) {
        echo $a, $b;
    }

    public function doSomething(array $things) {
        $theEchoFunction = $this->echoIt; // save it for the next line

        // Get into a closure and pass the method as a variable
        array_map(function($thing) use ($theEchoFunction) { // <-- this is the bit I'd like to do
            // Call the function directly from the variable
            $theEchoFunction($thing[0], $thing[1]);
        }, $things);
    }
}

我知道做$that = $this;很簡單$that = $this; 然后將$that傳遞給閉包,但這意味着我無法訪問$that->echoIt因為它受到了保護。 是否可以將方法本身發送給閉包?

我猜這個問題實際上可能是X / Y問題 我想做的是從閉包內部調用受保護的方法。 我只想傳遞該方法,以便閉包不需要知道該類具有echoIt方法。

具體來說,這可以很好地完成*(在PHP和Javascript中):

class A
{

    protected function echoIt($a, $b) {
        echo $a, $b;
    }

    public function doSomething(array $things) {
        array_map(function ($thing) {
            $this->echoIt($thing[0], $thing[1]);
        }, $things);
    }

}

假設這只是一個測試設置,而您確實需要在變量中傳遞回調,則可以使用callable偽類型來實現

class A
{

    protected function echoIt($a, $b) {
        echo $a, $b;
    }

    public function doSomething(array $things) {
        $callback = [$this, 'echoIt'];
        array_map(function ($thing) use ($callback) {
            $callback($thing[0], $thing[1]);
        }, $things);
    }

}

*自PHP 5.4起。

class Test
{
    protected function echoIt($a, $b) {
        echo $a, $b;
    }

    public function doSomething(array $things) {
        $theEchoFunction = function($a, $b) {
            return $this->echoIt($a, $b);
        };

        array_map(function($thing) use ($theEchoFunction) {
            $theEchoFunction($thing[0], $thing[1]);
        }, $things);
    }
}

$test = new Test();
$test->doSomething(["1", "2"]);

結果

12

這對我有用,我不知道它是否按您的預期工作。 但是要將方法分配給變量,您需要使變量可調用。 因此,我認為您可以創建一個包裝在受保護方法之上的匿名函數。 然后,您將該函數傳遞給閉包。

暫無
暫無

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

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