note 97296 added to functions.anonymous

From: Date: Tue, 13 Apr 2010 01:53:26 +0000
Subject: note 97296 added to functions.anonymous
Groups: php.notes 
Request: Send a blank email to php-notes+get-168183@lists.php.net to get a copy of this message
In the code <?php function new_counter() { $counter = mt_rand(); return function()use(&$counter) { return ++$counter; }; } $t1 = new_counter(); $t2 = new_counter(); echo $t1(),"\n"; echo $t1(),"\n"; echo $t2(),"\n"; echo $t2(),"\n"; echo $t1(),"\n"; echo $t1(),"\n"; ?> The variable $counter is local to new_counter() and is used by reference by the returned lambda function. Because $counter is not static, a new variable is created each time new_counter() is called. But because the lambda function uses a REFERENCE to the $counter variable - and not a new local variable with a copy of the value $counter had when the lambda function was constructed - the $counter variable created when new_counter() ran still exists (because a reference to it still exists). Every lambda function has a variable reference "hardwired" into it. That variable therefore persists across calls to the lambda function - rather like a static variable. But that variable is only LOCAL to the new_counter() function that created it. As soon as new_counter() returns, it gives up its reference to $counter. When new_counter() is called again, it gets allocated a NEW $counter variable and gives a reference to THAT variable to the lambda function it constructs. So the lambda functions in $t1 and $t2 each have their OWN $counter variable - separate from the other's, which persists from one call to the next. The effect is very similar to declaring and initialising $counter as static within the lambda function - and then it doesn't need to use anything from new_counter() - but you can't initialise a static variable with a function call like mt_rand()! ---- Server IP: 202.89.58.1 Probable Submitter: 125.237.144.87 ---- Manual Page -- http://www.php.net/manual/en/functions.anonymous.php Edit -- https://master.php.net/note/edit/97296 Del: integrated -- https://master.php.net/note/delete/97296/integrated Del: useless -- https://master.php.net/note/delete/97296/useless Del: bad code -- https://master.php.net/note/delete/97296/bad+code Del: spam -- https://master.php.net/note/delete/97296/spam Del: non-english -- https://master.php.net/note/delete/97296/non-english Del: in docs -- https://master.php.net/note/delete/97296/in+docs Del: other reasons-- https://master.php.net/note/delete/97296 Reject -- https://master.php.net/note/reject/97296 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#168183) next »