Search code examples
phpphp-5.3

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?


Solution

  • 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;
    }