NeuronQ
NeuronQ

Reputation: 8195

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?

Upvotes: 3

Views: 179

Answers (2)

SDC
SDC

Reputation: 14222

Simple answer: What you're asking for cannot be done in PHP versions older than 5.3. Sorry, but the functionality simply is not available. There aren't even any useful work-arounds (besides using global variables of course).

However, if you are using a version of PHP older than 5.3, I would strongly advise you to upgrade.

5.2 was declared end of life two years ago, and has had zero support or security fixes since then -- it is unsupported and insecure.

In addition, that lack of support also extends to operating systems. For most server operating systems, installers for 5.2 and earlier do not exist for current OS versions. This means that if you're running PHP 5.2, it follows that you're likely to also be running an obsolete OS version. This also has security implications.

No sys admin worth his pay would allow his network to run known-insecure software on a publicly-accessible system, so if you haven't upgraded already, you really need to do so now.

If you're using a web hosting company that hasn't upgraded, you should be considering moving your business to a company that cares about the security of their network.

Upvotes: 0

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

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.

Upvotes: 5

Related Questions