55

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?

3 Answers 3

124
+50

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
5
  • 6
    Ahh good job fella! I totally forgot about the use keyword! +1 for you! I'm using ColdFusion these days... No anonymous functions for me :( Sep 14, 2011 at 14:06
  • very nice i learned so much about closers now.i have also used it in my code.very good answer
    – sumi
    Sep 28, 2011 at 6:27
  • 2
    In PHP context anonymous functions and closures are used interchangeably, although there is a difference. The current implementation even uses Closure as the underlying class for all anonymous functions regardless of them being real closures (capturing the outer context). The term function object is not really important in this question context. Sep 29, 2011 at 14:52
  • 2
    +1 So, what you're saying is: the implementers of PHP don't know what a Closure is? Yea.. I can believe that.
    – lsl
    Sep 30, 2011 at 0:16
  • 2
    @Louis No. He only says that PHP has a different, somewhat more intuitive closure implementation then JavaScript. It doesn't mean that either of the implementations is wrong. They're just different.
    – NikiC
    Sep 30, 2011 at 6:44
4

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...

3
  • Why would you want to typecast an anonymous function? Sep 14, 2011 at 14:05
  • If you have a function that requires an array as its argument an anonymous function will fail that coercion attempt, unless I've missed the boat and they base the required value type on the functions final return value/type.. Sep 14, 2011 at 14:09
  • Of course in your example you are screwed if you want to set $readout to null, 0, the empty string, etc. Sep 14, 2011 at 14:48
2

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
}
3
  • 4
    you have to stretch "pretty much" a lot to really say they work the same way :)
    – Gordon
    Sep 14, 2011 at 13:55
  • 1
    Call me blind but I don't see that much of a difference :)
    – Rijk
    Sep 14, 2011 at 13:56
  • I'm with Rijk on this, from what I've seen and used I don't see any measurable difference.. Sep 14, 2011 at 14:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.