简体   繁体   中英

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 :)

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.

Try again with this (you have 2 ,, too much at the end of the code and please remove the static)

EDIT: adding function so you can use the array from other class.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM