note 39091 modified in language.variables.scope by danbrown
| From: | danbrown@php.net | Date: | Mon, 18 May 2009 01:41:12 +0000 |
| Subject: | note 39091 modified in language.variables.scope by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-155575@lists.php.net to get a copy of this message | ||
Whats good for the goose is not always good for the iterative gander. If you declare and initialize
the static variable more than once inside a function ie.
<?php
function Test(){
static $count = 0;
static $count = 1;
static $count = 2;
echo $count;
}
?>
the variable will take the value of the last declaration. In this case $count=2.
But! however when you make that function recursive ie.
<?php
function Test(){
static $count = 0;
static $count = 1;
static $count = 2;
$count++;
echo $count;
if ($count<10){
Test();
}
}
?>
Every call to the function Test() is a differenct SCOPE and therefore the static declarations and
initializations are NOT executed again. So what Im trying to say is that its OK to declare and
initialize a static variable multiple times if you are in one function... but its NOT OK to declare
and initialize a static variable multiple times if you call that same function multiple times. In
other words the static variable is set once you LEAVE a function (even if you go back into that very
same function).
--was--
Whats good for the goose is not always good for the iterative gander. If you declare and initialize
the static variable more than once inside a function ie.
function Test(){
static $count = 0;
static $count = 1;
static $count = 2;
echo $count;
}
the variable will take the value of the last declaration. In this case $count=2.
But! however when you make that function recursive ie.
function Test(){
static $count = 0;
static $count = 1;
static $count = 2;
$count++;
echo $count;
if ($count<10){
Test();
}
}
Every call to the function Test() is a differenct SCOPE and therefore the static declarations and
initializations are NOT executed again. So what Im trying to say is that its OK to declare and
initialize a static variable multiple times if you are in one function... but its NOT OK to declare
and initialize a static variable multiple times if you call that same function multiple times. In
other words the static variable is set once you LEAVE a function (even if you go back into that very
same function).
http://php.net/manual/en/language.variables.scope.php