`static` keyword inside function? `static` keyword inside function? php php

`static` keyword inside function?


It makes the function remember the value of the given variable ($has_run in your example) between multiple calls.

You could use this for different purposes, for example:

function doStuff() {  static $cache = null;  if ($cache === null) {     $cache = '%heavy database stuff or something%';  }  // code using $cache}

In this example, the if would only be executed once. Even if multiple calls to doStuff would occur.


Seems like nobody mentioned so far, that static variables inside different instances of the same class remain their state. So be careful when writing OOP code.

Consider this:

class Foo{    public function call()    {        static $test = 0;        $test++;        echo $test . PHP_EOL;     }}$a = new Foo();$a->call(); // 1$a->call(); // 2$a->call(); // 3$b = new Foo();$b->call(); // 4$b->call(); // 5

If you want a static variable to remember its state only for current class instance, you'd better stick to a class property, like this:

class Bar{    private $test = 0;    public function call()    {        $this->test++;        echo $this->test . PHP_EOL;     }}$a = new Bar();$a->call(); // 1$a->call(); // 2$a->call(); // 3$b = new Bar();$b->call(); // 1$b->call(); // 2


Given the following example:

function a($s){    static $v = 10;    echo $v;    $v = $s;}

First call of

a(20);

will output 10, then $v to be 20. The variable $v is not garbage collected after the function ends, as it is a static (non-dynamic) variable. The variable will stay within its scope until the script totally ends.

Therefore, the following call of

a(15);

will then output 20, and then set $v to be 15.