Today I Learned - Rocky Kev

TIL the difference of Closures in Javascript vs PHP

POSTED ON:

TAGS:

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.

source

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:

TIL how NGINX knows to look for index.html vs index.php

What happens when visitor hits /foo/bar URL?

TIL php-fpm

PHP runs as a separated service when using PHP-FPM. By using this PHP version as language interpreter, requests are processed through a TCP/IP socket; so that the Nginx web server only handles the HTTP requests and PHP-FPM interprets the PHP code. The fact of having two separate services is key for increasing efficiency.

TIL the difference between single-threaded & multi-threaded architecture

For web dev, we don't need it. We're not bottle-necked by the processing power. We're instead bottlenecked by the ability to read files/databases. We can simulate multi-threading (and improve our app's performance) using async/await.