sant
sant

Reputation: 21

PHP parse error while creating closures on a Class static variable

I am using 5.3.10 and trying to create closures in following manner, but it gives parse error. Can anyone tell me why it is giving parse error?

class ABC {
    public static $funcs = array(
        'world' => function() {
            echo "Hello,";
            echo "World!\n";
        },
        'universe' => function() {
            echo "Hello,";
            echo "Universe!\n";
        },
    ); 
}

Upvotes: 1

Views: 907

Answers (2)

Moe
Moe

Reputation: 2730

The reason why this is not working is that in PHP it is not allowed to assign a closure directly to a (static) class variable initializer.

So for your code to work, you have to use this workaround:

<?php

class ABC {
    public static $funcs;
}

ABC::$funcs  = array(
        'world' => function() {
            echo "Hello,";
            echo "World!\n";
        },
        'universe' => function() {
            echo "Hello,";
            echo "Universe!\n";
        },
);

$func = ABC::$funcs['world'];
$func();

The workaround is taken from the answer to this question on Stack Overflow: PHP: How to initialize static variables

Btw, notice that it is also not possible to call the function directly via ABC::$funcs['world'](). For this to work you would have to use PHP >= 5.4 which introduced function array dereferencing.

Upvotes: 4

keithhatfield
keithhatfield

Reputation: 3273

Static properties can only be initialized using literals or constants. From the PHP manual at http://php.net/manual/en/language.oop5.static.php:

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

Upvotes: 0

Related Questions