开发者

Can't invoke a closure wrapped in a closure?

开发者 https://www.devze.com 2023-04-09 13:47 出处:网络
If I wrap a closure in another closure, I can\'t invoke the nested closure. Why not? I think an example illustrates the problem best.

If I wrap a closure in another closure, I can't invoke the nested closure. Why not? I think an example illustrates the problem best.

This PHP code:

function FInvoke($func) {
    $func();
}

FInvoke(function () { echo "Direct Invoke Worked\n"; });

Works as expected and prints "Direct Invoke Worked".

Ho开发者_Go百科wever, If I slightly modify it to add another level of indirection, it fails:

function FInvoke($func) {
    $func();
}

function FIndirectInvoke($func) {
    FInvoke(function () {
        $func();
    });
}

FIndirectInvoke(function () { echo "Never makes it here"; });

The failure message is "Fatal error: Function name must be a string in file.php on line X"


you have to pass $func to the inner lambda using "use" keyword

function FInvoke($func) {
    $func();
}

function FIndirectInvoke($func) {
    FInvoke(function () use($func) { // <--- here
        $func();
    });
}

FIndirectInvoke(function () { echo "ok"; });
0

精彩评论

暂无评论...
验证码 换一张
取 消