Alexis Wilke
Alexis Wilke

Reputation: 20771

"PHP Fatal error: Constant expression contains invalid operations", when initializing a static inline?

I am wondering why is it that my static variable initialization does not work with the following declaration:

function validate()
{
    static $timezones = DateTimeZone::listIdentifiers(); // Error here

    ...
}

The line with static ... generates the error:

PHP Fatal error: Constant expression contains invalid operations

If I do the following, though, it works as expected:

function validate()
{
    static $timezones = null;
    if(!isset($timezones))
    {
        $timezones = DateTimeZone::listIdentifiers();
    }
    ...
}

So I have a way around the problem, but I am wondering why is it that the first method fails?

Upvotes: 1

Views: 2700

Answers (1)

Anar Bayramov
Anar Bayramov

Reputation: 11594

Based on php documentation; You cannot initialize static variable with another non constant expression or variable.

Which means if you want to assign a value to static variable this value should be a an integer, string etc.

What you did here is against static word rule in PHP you are assigning a dynamic value to $timezones variable

static $timezones = DateTimeZone::listIdentifiers(); // Error here

Check for detailed information.

http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static

Upvotes: 2

Related Questions