Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real closure in PHP <5.3

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?

like image 335
NeuronQ Avatar asked Jul 11 '26 10:07

NeuronQ


1 Answers

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.

like image 118
Stefan Gehrig Avatar answered Jul 14 '26 08:07

Stefan Gehrig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!