note 52294 added to language.variables.scope
| From: | php-general at lists dot php dot net | Date: | Wed, 27 Apr 2005 11:46:10 +0000 |
| Subject: | note 52294 added to language.variables.scope | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-88613@lists.php.net to get a copy of this message | ||
Be careful if your static variable is an array and you return
one of it's elements: Other than a scalar variable, elements
of an array are returned as reference (regardless if you
didn't define them to be returned by reference).
<?php
function incr(&$int) {
return $int++;
}
function return_copyof_scalar() {
static $v;
if (!$v)
$v = 1;
return($v);
}
function return_copyof_arrayelement() {
static $v;
if (!$v) {
$v = array();
$v[0] = 1;
}
return($v[0]);
}
echo "scalar: ".
incr(return_copyof_scalar()).
incr(return_copyof_scalar()).
"\n";
echo "arrayelement: ".
incr(return_copyof_arrayelement()).
incr(return_copyof_arrayelement()).
"\n";
?>
Should print
scalar: 11
arrayelement: 11
but it prints:
scalar: 11
arrayelement: 12
as in the second case the arrays element was returned by
reference. According to a guy from the bug reports the
explanation for this behaviour should be somewhere here in
the documentation (in 'the part with title: "References with
global and static variables"'). Unfortunately I can't find
anything about that here. As the guys from the bug reports
are surely right in every case, maybe there is something
missing in the documentation. Sadly I don't have a good
explanation why this happens, so I decided to document at
least the behaviour.
----
Manual Page -- http://www.php.net/manual/en/language.variables.scope.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+52294
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52294&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52294&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52294&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52294&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52294&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+52294&report=yes
Search -- http://master.php.net/manage/user-notes.php