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";
        },
    ); 
}
hakre
  • 193,403
  • 52
  • 435
  • 836
sant
  • 21
  • 2

2 Answers2

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.

Community
  • 1
  • 1
Michael Osl
  • 2,720
  • 1
  • 21
  • 36
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.

keithhatfield
  • 3,273
  • 1
  • 17
  • 24