Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't invoke a closure wrapped in a closure?

Tags:

php

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".

However, 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"

like image 859
Jon Hess Avatar asked Feb 22 '23 20:02

Jon Hess


1 Answers

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"; });
like image 137
user187291 Avatar answered Mar 04 '23 05:03

user187291