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