Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are PHP closures broken or am I missing something?

Tags:

closures

php

I've been reading on the new features of PHP 5.3, and one of the major features are closures.

Unless I'm very badly mistaken, the PHP developers are either:
a) confusing closures with just anonymous functions
b) the closures are broken in PHP 5.3.1 in which I'm testing

From what wikipedia says closures are the mechanism of anonymous functions plus the binding of the function's parent's scope variables to the function's scope. The last part seems broken in PHP.

I've checked PHP bugs, and found nothing about this, strangely.

Here's how I'm testing:

<?php

function getFun() {
    $x = 2;
    return function() {
        return $x;
    };
}
$f = getFun(); // getFun()(); doesn't work -.-
var_dump($f()); // $f() == null

In languages that actually implement closures, it returns 2:

def f():
    x = 2
    return lambda: x
print(f()()) # prints 2

and

alert((function() {
    var x = 2;
    return function() {
        return x;
    };
})()()); // alerts 2

So, am I wrong or?

like image 255
Prody Avatar asked Jan 01 '10 19:01

Prody


People also ask

What are PHP closures?

Basically a closure in PHP is a function that can be created without a specified name - an anonymous function. Here's a closure function created as the second parameter of array_walk() . By specifying the $v parameter as a reference one can modify each value in the original array through the closure function.

What is closure in PHP and why does it use use identifier?

The closure is a function assigned to a variable, so you can pass it around. A closure is a separate namespace, normally, you can not access variables defined outside of this namespace. There comes the use keyword: use allows you to access (use) the succeeding variables inside the closure.

Are all functions closures?

But as explained above, in JavaScript, all functions are naturally closures (there is only one exception, to be covered in The "new Function" syntax). That is: they automatically remember where they were created using a hidden [[Environment]] property, and then their code can access outer variables.

Is a closure callable?

In PHP, a closure is a callable class, to which you've bound your parameters manually.


1 Answers

variables inherited from the outer scope need to be listed explicitely. from the manual:

public function getTotal($tax)
{
    $total = 0.00;

    $callback =
        function ($quantity, $product) use ($tax, &$total)
...
like image 179
just somebody Avatar answered Sep 17 '22 13:09

just somebody