1

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";
        },
    ); 
}

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.