Howard
Howard

Reputation: 19825

Advantage of PHP's explicit variable when used in closure

In PHP, if you want to access variable in the outer scope, you need to declare it explicitly, e.g.

$foo = 'bar';
func (function() use ($foo) {

    echo $foo;

});

But in JavaScript, they are implicit, e.g.

foo = 'bar';
func (function() {
    console.log(foo);
});

What are the advantages and disadvantage of these two type of closure?

Upvotes: 1

Views: 329

Answers (2)

webbiedave
webbiedave

Reputation: 48887

In PHP, if you want to access variable in the outer scope, you need to declare it explicitly [...] use ($foo)

Technically, your function is not accessing $foo in the outer scope. To do that, you would need to:

$foo = 'bar';
$func = function() {
    global $foo;
    echo $foo;
};

This is not a closure. No variables are closed in with the function. If the value of $foo is changed, the next call to func will reflect that:

$func(); // bar
$foo = 'baz';
$func(); // baz

However, if we close in $foo with func:

$foo = 'bar';
$func = function() use ($foo) {
    echo $foo;
};

$func(); // bar
$foo = 'baz';
$func(); // bar

func's $foo will retain it's value because it's been closed-over into the function.

To do the same in JavaScript, you simply create a function within a function and a closure will be created (giving the inner function access to the enclosing function's scope):

function getFunc(foo) {
    return function () {
        console.log(foo);
    };
}

foo = "bar";
func = getFunc(foo);
func(); // bar
foo = "baz";
func(); // bar

What are the advantages and disadvantage of these two type of closure?

Using a "heap" type scope, as opposed to stack, so that the variable environment stays attached to the function allows first-class functions to be much more flexible as they can be passed around and recalled without worrying about creating (or passing in) a certain set of variables in order to make the function usable.

Upvotes: 2

ricochet1k
ricochet1k

Reputation: 1252

PHP does this because it doesn't know otherwise whether you meant to use the outer variable or not, since an unset variable acts like an empty string. This type of closure is therefore required for PHP, but not for Javascript.

Upvotes: 0

Related Questions