note 78778 added to language.variables.scope
| From: | SIDTRIVEDI at osu1 dot php dot net | Date: | Sat, 27 Oct 2007 09:46:23 +0000 |
| Subject: | note 78778 added to language.variables.scope | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-131772@lists.php.net to get a copy of this message | ||
<?php
/*
VARIABLE SCOPE : GLOBAL V/S STATIC
If variable $count is defined global as under, instead of static, it does not work well as desired
in repeated function calls.
$count = 1; //if not defined STATIC, in each function call, it starts countig from one to 25.
global $count;
which gives folowing output:
0123456789101112131415161718192021222324
Total 24 numbers are printed.
So far 26 function call(s) made.
26272829303132333435363738394041424344454647484950
Total 50 numbers are printed.
So far 52 function call(s) made.
*/
function print_1to50()
{
// $count = 1;
// global $count;
static $count=1; // Initial assigment of One to $count, static declarion holds the last(previous)
value of variable $count in each next function calls.
$limit = $count+24;
while($count<=$limit)
{
echo "$count";
$count=$count+1;
}
$num_count= $count-1;
echo "<br>\n". "Total $num_count numbers are printed.<br>";
return; // return statement without parenthesis()or arguments denotes end of a function
rather than returning any values to subsequent function call(s).
} // end of while loop
$count=0;
print_1to50();
$count=$count+1;
print "So far $count function call(s) made.<br><br>";
print_1to50();
$count=$count+1;
print "So far $count function call(s) made.<br>";
/*
Which gives following output:
12345678910111213141516171819202122232425
Now I have printed 25 numbers.
I have made 1 function call(s).
26272829303132333435363738394041424344454647484950
Now I have printed 50 numbers.
I have made 2 function call(s).
*/
?>
----
Server IP: 69.147.83.197
Probable Submitter: 208.72.122.18
----
Manual Page -- http://www.php.net/manual/en/language.variables.scope.php
Edit -- https://master.php.net/note/edit/78778
Del: integrated -- https://master.php.net/note/delete/78778/integrated
Del: useless -- https://master.php.net/note/delete/78778/useless
Del: bad code -- https://master.php.net/note/delete/78778/bad+code
Del: spam -- https://master.php.net/note/delete/78778/spam
Del: non-english -- https://master.php.net/note/delete/78778/non-english
Del: in docs -- https://master.php.net/note/delete/78778/in+docs
Del: other reasons-- https://master.php.net/note/delete/78778
Reject -- https://master.php.net/note/reject/78778
Search -- https://master.php.net/manage/user-notes.php