note 41213 added to language.variables.scope
| From: | Randolpho at rn2 dot php dot net | Date: | Fri, 02 Apr 2004 17:53:30 +0000 |
| Subject: | note 41213 added to language.variables.scope | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-67530@lists.php.net to get a copy of this message | ||
More on static variables:
My first not is probably intuitive to most, but I didn't notice it mentioned explicitly, so
I'll mention it: 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:
<?
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. :)
----
Manual Page -- http://www.php.net/manual/en/language.variables.scope.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+41213
Delete -- http://master.php.net/manage/user-notes.php?action=delete+41213&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+41213&report=yes
Search -- http://master.php.net/manage/user-notes.php