Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53597

static in php behaves strangly, can't accept functions

This code throws parse error, which I do not understand why.

function t(){
 return 'g';
}
function l(){
    static $b = t();
    return $b;
}
l();

The question is, why?

Upvotes: 4

Views: 53

Answers (2)

Mark Baker
Mark Baker

Reputation: 212412

Quoting from the manual:

Note:

Trying to assign values to these [static] variables which are the result of expressions will cause a parse error.

(my emphasis)

c.f. http://www.php.net/manual/en/language.variables.scope.php Example #7

Upvotes: 10

zerkms
zerkms

Reputation: 254896

static variables values are filled on source parsing step, thus they cannot contain non-constant values.

You could implement the value initialization with something like:

function l(){
    static $b;
    if (!$b) $b = t();
    return $b;
}

Upvotes: 7

Related Questions