TIL the difference of Closures in Javascript vs PHP
POSTED ON:
TAGS: php javascript closure
I never knew PHP and Javascript closures were different.
I read the comment below and had to dig deeper:
This caused me some confusion a while back when I was still learning what closures were and how to use them, but what is referred to as a closure in PHP isn't the same thing as what they call closures in other languages (E.G. JavaScript).
In JavaScript, a closure can be thought of as a scope, when you define a function, it silently inherits the scope it's defined in, which is called its closure, and it retains that no matter where it's used. It's possible for multiple functions to share the same closure, and they can have access to multiple closures as long as they are within their accessible scope.
In PHP, a closure is a callable class, to which you've bound your parameters manually.
From PHP Manual - chuck at bajax dot us
Let's start there.
PHP Closures:
Basically a closure in PHP is a function that can be created without a specified name - an anonymous function.
$var = function() {
return 'I am a ' . func_get_arg(0);
};
print_r($var('Closure'));
There's some local scope involved.
JS Closures:
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function.
a = (function () {
var privatefunction = function () {
alert('hello');
}
return {
publicfunction : function () {
privatefunction();
}
}
})();
So now you can create functions and data, and keep it within the outer scope, and only referenced in the inner scope.
A real example:
var updateClickCount = (function(){
var counter = 0;
return function(){
++counter;
// Do something with counter
}
})();
Related TILs
Tagged: php