Javascript closures vs PHP closures, what's the difference?

PhpJavascriptClosures

Php Problem Overview


What are the differences between closures in JS and closures in PHP? Do they pretty much work the same way? Are there any caveats to be aware of when writing closures in PHP?

Php Solutions


Solution 1 - Php

One difference is how both cope with storing the context in which an anonymous function is executed:

// JavaScript:
var a = 1;
var f = function() {
   console.log(a);
};
a = 2;
f();
// will echo 2;

// PHP
$a = 1;
$f = function() {
    echo $a;
};
$a = 2;
$f();
// will result in a "PHP Notice:  Undefined variable: a in Untitled.php on line 5"

To fix this notice you'll have to use the use syntax:

$a = 1;
$f = function() use ($a) {
    echo $a;
};
$a = 2;
$f();
// but this will echo 1 instead of 2 (like JavaScript)

To have the anonymous function behave somehow like the JavaScript counterpart you'll have to use references:

$a = 1;
$f = function() use (&$a) {
    echo $a;
};
$a = 2;
$f();
// will echo 2

I think this is the most striking difference between JavaScript and PHP closures.

Second difference is that every JavaScript closure has a this context available which means, that you can use this inside the closure itself (although it's often quite complicated to figure out what this actually refers to) - PHP's current stable version (PHP 5.3) does not yet support $this inside a closure, but PHP's upcoming version (PHP 5.4) will support $this binding and rebinding using $closure->bind($this) (See the Object Extension RFC for more info.)

Third difference is how both languages treat closures assigned to object properties:

// JavaScript
var a = {
    b: function() {}
};
a.b(); // works


// PHP
$a = new stdClass();
$a->b = function() {};
$a->b(); // does not work "PHP Fatal error:  Call to undefined method stdClass::b() in Untitled.php on line 4"

$f = $a->b;
$f(); // works though

The same is true if closures are assigned to properties in class definitions:

class A {
    public $b;

    public function __construct() {
        $this->b = function() {};
    }
    
    public function c() {
        $this->b();
    }
}
$a = new A();
// neither
$a->b();
// nor
$a->c();
// do work

Fourth difference: JavaScript Closures are full fledged objects, wheres in PHP they are restricted objects. For instance, PHP Closures cannot have properties of their own:

$fn = function() {};
$fn->foo = 1;
// -> Catchable fatal error: Closure object cannot have properties

while in JavaScript you can do:

var fn = function() {};
fn.foo = 1;
fn.foo; // 1

Fifth difference: Returned closures can be immediately called upon in Javascript:

var fn = function() { return function() { alert('Hi');}}
fn()();    

Not in PHP:

$fn = function() { return function() { echo('Hi');};};
$fn()();     // syntax error

Solution 2 - Php

The only thing I've found in PHP (that is totally cool and really handy!) is the ability to use them as getters and setters in classes which was always a nightmare to achieve before, JavaScript can be used in the same way but they do both act almost identically from what I've seen.

I'm not sure about the namespacing convention differences between the two but as @Rijk pointed out there is a section on the PHP website dedicated to them

<?php 
    class testing {
        private $foo = 'Hello ';
        public $bar  = 'Bar';

        #Act like a getter and setter!
        public static $readout = function ($val = null) {
            if (!empty($val)) {
                testing::$readout = $val;
            }
            return testing::$readout;
        }
    }

They are also really great for...

Looping through items with a controller rather than a new for/each loop on the page

Great for supplying as arguments to functions/classes

Whats annoying about them is...

You can't typecast them, since they're just functions...

Solution 3 - Php

They do pretty much work the same way. Here's more information about the PHP implementation: http://php.net/manual/en/functions.anonymous.php

You can use a closure (in PHP called 'anonymous function') as a callback:

// return array of ids
return array_map( function( $a ) { return $a['item_id']; }, $items_arr );

and assign it to a variable:

$greet = function( $string ) { echo 'Hello ' . $string; }; // note the ; !
echo $greet('Rijk'); // "Hello Rijk"

Furthermore, anonymous function 'inherit' the scope in which they were defined - just as the JS implementation, with one gotcha: you have to list all variables you want to inherit in a use():

function normalFunction( $parameter ) {
    $anonymous = function() use( $parameter ) { /* ... */ };
}

and as a reference if you want to modify the orignal variable.

function normalFunction( $parameter ) {
    $anonymous = function() use( &$parameter ) { $parameter ++ };
    $anonymous();
    $parameter; // will be + 1
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionaziz punjaniView Question on Stackoverflow
Solution 1 - PhpStefan GehrigView Answer on Stackoverflow
Solution 2 - PhpDave MackintoshView Answer on Stackoverflow
Solution 3 - PhpRijkView Answer on Stackoverflow