Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Static Variable Outside A Method

<?php


namespace x {
    foreach([1,2] as $i) {
        static $s = 0;
        
        print $s + $i;
        ++$s;
    }
    
}

// 13

?>

TIL that PHP static variables can be declared out of a function, in the namespace.

Then, it is a simple variable with a default value. There is no way to call the global scope again (that makes no sense). In fact, including the same file simply restarts the context and the static variable again.

May be a warning from the linter could be nice.

In PHP 8.3, duplicate ‘static’ variable definitions is forbidden. Not in a loop, which is a bad practice anyway.

See Also

PHP Features

Last updated: 10 September 2026