Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php function inside array

I try to store a function inside an array but it keeps giving me this error:

unexpected 'function' (T_FUNCTION)

I looked around on internet but they mostly say that I should be using php version 5.3 and above, while I am using 5.6.21.

Here is my array:

       static $Events = array(
            'View Page' => array(
                'properties' => array(
                    'previous_event',
                    'number_view_page',
                ),
                'trigger' => function($foo){
                    return $foo;
                },
            ),
        );

If anyone knows what the problem is and how to solve it, please help me :)

like image 550
Lars Spaenij Avatar asked Apr 16 '26 14:04

Lars Spaenij


1 Answers

static values need to be initialised with static/constant expressions. Sadly, anonymous functions aren't "constant" enough to count. Later PHP versions allow some limited expressions like 2 + 4 (because the result is always constant), but nothing more than that. Function declarations are too complex to handle in a static context (you can add a function to the array afterwards at any time, you just can't initialise it that way*).

* The reason for this restriction is that static declarations are handled at a different parsing phase than runtime code, and that parsing phase cannot handle anything but primitive values.

like image 184
deceze Avatar answered Apr 19 '26 02:04

deceze