Closures in PHP, Javascript and Elixir

Closures in PHP, Javascript and Elixir

Closures are one of the fundamental building blocks of functional programming techniques.
A Closure is a construct that permits to bind the definition of a function together a particular scope, normally implemented via anonymous functions.
They are particularly important, for example in the implementation of event callbacks.
Let’s see how they work in three different languages: PHP, Javascript and Elixir.

PHP is not -traditionally- a programming language strictly functional and to code following the functional programming paradigm we need some of the features added in the last versions, specifically PHP 5.3.

The $a variable value is copied to the closure function scope via the ‘use’ keyword.
Note that we must explicit declare the variable we want to inherit inside the closure scope. From PHP 5.4 the $this special variable is inherited automatically.

We don’t need to explicitly “pass in” the variables same as in PHP: the closure “grabs” automatically all the variables in the outer scope.
And there is another difference, more important: the variables are bound by reference, if we mutate the data in the outer scope, the closure value will change.