Stphane Stphane - 1 year ago 131
PHP Question

Use a class static variable as part of a closure use list

I would like to "use" a static class variable as part as the use list statement of a closure ?

Following snippets simply fail as unexpected 'self' parse errors.

array_walk($_categories, function($c, $i) use (&self::$tree) {


array_walk($_categories, function($c, $i) use (self::&$tree) {

Parse error: syntax error, unexpected 'self' (T_STRING), expecting variable (T_VARIABLE)

Is there any special syntax to use in this very special case ?

Answer Source

Why on earth would you want to do that? Given your use of self, the closure is clearly defined within the class somewhere, so you're able to access the static member anyway:

class Foo
    protected static $bar = 123;

    public function test()
        return function($x) {
            static::$bar += $x; // or self::$bar
            return static::$bar;

$x = new Foo;
$y = $x->test();


No need to muck about with references at all...

If you're on an EOL'ed version of PHP (5.3 for example), you could work around the problem by assigning a reference to the static member first, and then pass a reference to that reference via use:

public function test()
    $staticRef = &static::$bar;
    return function($x) use (&$staticRef) {
        $staticRef += $x;
        return $staticRef;

But if you're still working with a version of PHP that was EOL'ed long ago, really you should be upgrading...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download