php static variable usage

Sometimes we may need to call a function repeatedly. Some variables in it do not need to be initialized repeatedly, and the initialization cost is relatively high. We can use the static keyword to modify it. The initialization is performed when the variable is not initialized, and the initialized variable is no longer initialization. Such as:

function test()
{
    echo __FUNCTION__ . "\n";
    return mt_rand(10, 20);
}

function call()
{
    static $test;
    if (is_null($test)) {
        $test = test();
    }
    
    echo $test . "\n";
}

call();
call();
call();

 

The above will output:

test
13
13
13

  

What scenarios will it be used in? For example, the initialized variable may come from a database query, and the query result will not change in this request. Perhaps a method that everyone thinks of is to initialize outside the method, and then pass the initialized variable as a parameter, but this will add an unnecessary parameter (of course, if the initialization requires external conditions, say otherwise ), and the logic that originally appeared inside the function is placed outside the function, so that if the method is also called elsewhere, a repeated initialization operation will be performed, and the code will be redundant.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325289142&siteId=291194637