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"
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"; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With