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?
Technically, your function is not accessing
$fooin the outer scope. To do that, you would need to:This is not a closure. No variables are closed in with the function. If the value of
$foois changed, the next call tofuncwill reflect that:However, if we close in
$foowithfunc:func‘s$foowill 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):
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.