|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2011-02-18 00:49 UTC] a at b dot c dot de
Description:
------------
Let an ordinary function declare a static local variable, and let it also define an anonymous function that uses that static variable. It can happen that the static variable no longer retains its value across calls to the ordinary function; i.e., it loses that static property.
It seems to be limited to situations where the anonymous function is defined before the static variable has had its value changed.
Test script:
---------------
function test_1()
{
static $v = 0;
++$v;
echo "Outer function increments \$v to $v\n";
$f = function()use($v)
{
echo "Inner function reckons \$v is $v\n";
};
return $f;
}
echo "\nIncrement static variable, then use it in anonymous function definition:\n";
$f = test_1(); $f();
$f = test_1(); $f();
function test_2()
{
static $v = 0;
$f = function()use($v)
{
echo "Inner function reckons \$v is $v\n";
};
++$v;
echo "Outer function increments \$v to $v\n";
return $f;
}
echo "\nUse static variable in anonymous function definition, then increment it:\n";
$f = test_2(); $f();
$f = test_2(); $f();
Expected result:
----------------
Increment static variable, then use it in anonymous function definition:
Outer function increments $v to 1
Inner function reckons $v is 1
Outer function increments $v to 2
Inner function reckons $v is 2
Use static variable in anonymous function definition, then increment it:
Outer function increments $v to 1
Inner function reckons $v is 0
Outer function increments $v to 2
Inner function reckons $v is 1
Actual result:
--------------
Increment static variable, then use it in anonymous function definition:
Outer function increments $v to 1
Inner function reckons $v is 1
Outer function increments $v to 2
Inner function reckons $v is 2
Use static variable in anonymous function definition, then increment it:
Outer function increments $v to 1
Inner function reckons $v is 0
Outer function increments $v to 1
Inner function reckons $v is 0
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Oct 27 23:00:01 2025 UTC |
A little further testing gives this: function test_1() { static $v = ''; $v .= 'b'; echo "Outer function catenates 'b' onto \$v to give $v\n"; $f = function()use($v) { echo "Inner function reckons \$v is $v\n"; }; $v .= 'a'; echo "Outer function catenates 'a' onto \$v to give $v\n"; return $f; } $f = test_1(); $f(); $f = test_1(); $f(); $f = test_1(); $f(); $f = test_1(); $f(); The second concatenation ('a') fails to be retained; if only the anonymous function didn't use($v), the variable would end up containing 'babababa'.