Search code examples
phpclosuresbind

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


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

Solution

  • As you've noticed, it doesn't really matter.

    It's like using the static keyword on a class method. You don't necessarily need it if you don't reference $this within the method (though this does violate strict standards).

    I suppose PHP can work out you mean the Closure to access A statically due to the null 2nd argument to bind()