0
votes

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?

1
Please stop tag spamming. Your post cannot possibly be C++ and PHP simultaneously, and that is absolutely NOT C++ code you posted. You're not new here; you know how tags work. Stop randomly adding them.Ken White
Why it fails explained in the error message.zerkms
@KenWhite Ah... Sorry, it was a suggested tag and since I do a lot of C++ too... Thanks for the edit.Alexis Wilke

1 Answers

2
votes

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