Is there any way to write real closures in PHP for language versions older than 5.3 (as 5.3 added the use keyword for anonymous functions)?
I PHP 5.3+ I can write:
function make_adder($x) {
return function($to) use ($x) {
return $to + $x;
};
}
$add5 = make_adder(5);
$add5(100); # => 105
How can I use this patterns of defining functions inside functions and the inner functions have access to outer function variables?
The following would work in this simple case:
function make_adder($x) {
return create_function('$to', 'return '.var_export($x, true).' + $to;');
}
$add5 = make_adder(5);
$add5(100); # => 105
But that's not a closure in its strict sense.
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