php closures: why the 'static' in the anonymous function declaration when binding to static class?

learning php picture learning php · Nov 11, 2013 · Viewed 9.5k times · Source

The example in the php documentation on Closure::bind include static on the anonymous function declaration. why? I can't find the difference if it is removed.

with:

class A {
    private static $sfoo = 1;
}
$cl1 = static function() { // notice the "static"
    return self::$sfoo;
};
$bcl1 = Closure::bind($cl1, null, 'A');
echo $bcl1(); // output: 1

without:

class A {
    private static $sfoo = 1;
}
$cl1 = function() {
    return self::$sfoo;
};
$bcl1 = Closure::bind($cl1, null, 'A');
echo $bcl1(); // output: 1

Answer

learning php picture learning php · Nov 12, 2013

found the difference: you can't bind static closures to object, only change the object scope.

class foo { }

$cl = static function() { };

Closure::bind($cl, new foo); // PHP Warning:  Cannot bind an instance to a static closure
Closure::bind($cl, null, 'foo') // you can change the closure scope