Jon Hess
Jon Hess

Reputation: 14257

Can't invoke a closure wrapped in a closure?

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"

Upvotes: 4

Views: 1198

Answers (1)

user187291
user187291

Reputation: 53950

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"; });

Upvotes: 8

Related Questions