note 41213 modified in language.variables.scope by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 01:40:49 +0000 |
| Subject: | note 41213 modified in language.variables.scope by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155574@lists.php.net to get a copy of this message | ||
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. :)
--was--
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. :)
http://php.net/manual/en/language.variables.scope.php