3

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

Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
  • 1
    It doesn't work because it is not implemeneted in php. http://stackoverflow.com/a/1633024/3595565 – Philipp Jun 15 '16 at 08:34

2 Answers2

3

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
1

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;
}
Johan Syah
  • 21
  • 4
  • This doesnt solve anything, and I am using static because this is inside a helper class so it can be used in any controller function – Lars Spaenij Jun 15 '16 at 08:05
  • you should create a function method inside your helper class that will return this array. then you can use it in your controller function. – Johan Syah Jun 15 '16 at 08:58