Misconceptions of a PHP Developer on Closures

I recently attended a Javascript meetup and one of the topics that we’re discussed is Javascript Closures. Armed with this knowledge, I explored closures back in my original language of PHP. I haven’t written any closures before in PHP hence, I had a hard time wrapping my head on this subject until I finally figured out these two distinctions.

First, closures and anonymous functions are not the same.

For Javascript developers, this is fairly obvious. But for PHP developers, it is one of the nuisance of the language that tripped me. In PHP, anonymous functions are automatically tag as objects with the class of “Closure”. This is a special class in the language such that new Closure object cannot be created by using the “new” keyword. In addition, only anonymous functions can have this class and assigning a named function to variable will throw an error.

$helloWorld = function() {
echo “Hello World!”;
echo get_class($helloWorld);  // Closure
// on the other hand, this will throw an error
$helloWorld = function helloWorld() {
echo "Hello World!";
echo get_class($helloWorld);  // PHP Parse error

Second, the definition of a closure that prevents a scope of parent function from being destroyed can only be replicated in PHP using the “use” keyword in the anonymous function and passing variables by reference. For example, the following closure in JS.

// JS Closure
function Order() {
var total = 0;
   return function addProduct(price) {
var salesTax = price * 0.12;
      total += price + salesTax;
      return total;
var myOrder = new Order();
console.log(myOrder(100)); // 112
console.log(myOrder(150)); // 280

Has the following equivalent in PHP.

function Order() {
$total = 0;
   return function($price) use (&$total) 
$salesTax = $price * 0.12;
$total += $price + $salesTax;
return $total;
$order = Order();
echo get_class($order); // Closure
echo $order(100); // 112
echo $order(150); // 280

Closures is a fairly new feature in PHP and it opens a lot of possibilities for PHP programmers (i.e. functional and callback style of programming). Hope this guide can help others in understanding closures in PHP.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.