note 41213 deleted from language.variables.scope by crell
| From: | crell@php.net | Date: | Thu, 31 Mar 2022 19:41:02 +0000 |
| Subject: | note 41213 deleted from language.variables.scope by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217934@lists.php.net to get a copy of this message | ||
Note Submitter: Randolpho
----
More on static variables:
A static variable does not retain it's value after the script's execution. Don't
count on it being available from one page request to the next; you'll have to use a database
for that.
Second, here's a good pattern to use for declaring a static variable based on some complex
logic:
<?php
function buildStaticVariable()
{
$foo = null;
// some complex expression or set of
// expressions/statements to build
// the return variable.
return $foo;
}
function functionWhichUsesStaticVar()
{
static $foo = null;
if($foo === null) $foo = buildStaticVariable();
// the rest of your code goes here.
}
?>
Using such a pattern allows you to separate the code that creates your default static variable value
from the function that uses it. Easier to maintain code is good. :)