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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I changed the event handling but still thank you! You explained it very clear!
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;
}

2 Comments

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
you should create a function method inside your helper class that will return this array. then you can use it in your controller function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.