note 99287 added to functions.anonymous
| From: | orls at osu1 dot php dot net | Date: | Mon, 09 Aug 2010 01:53:08 +0000 |
| Subject: | note 99287 added to functions.anonymous | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-171475@lists.php.net to get a copy of this message | ||
Watch out when 'importing' variables to a closure's scope -- it's easy to miss
/ forget that they are actually being *copied* into the closure's scope, rather than just being
made available.
So you will need to explicitly pass them in by reference if your closure cares about their contents
over time:
<?php
$result = 0;
$one = function()
{ var_dump($result); };
$two = function() use ($result)
{ var_dump($result); };
$three = function() use (&$result)
{ var_dump($result); };
$result++;
$one(); // outputs NULL: $result is not in scope
$two(); // outputs int(0): $result was copied
$three(); // outputs int(1)
?>
Another less trivial example with objects (what I actually tripped up on):
<?php
//set up variable in advance
$myInstance = null;
$broken = function() uses ($myInstance)
{
if(!empty($myInstance)) $myInstance->doSomething();
};
$working = function() uses (&$myInstance)
{
if(!empty($myInstance)) $myInstance->doSomething();
}
//$myInstance might be instantiated, might not be
if(SomeBusinessLogic::worked() == true)
{
$myInstance = new myClass();
}
$broken(); // will never do anything: $myInstance will ALWAYS be null inside this closure.
$working(); // will call doSomething if $myInstance is instantiated
?>
----
Server IP: 69.147.83.197
Probable Submitter: 94.194.100.108
----
Manual Page -- http://www.php.net/manual/en/functions.anonymous.php
Edit -- https://master.php.net/note/edit/99287
Del: integrated -- https://master.php.net/note/delete/99287/integrated
Del: useless -- https://master.php.net/note/delete/99287/useless
Del: bad code -- https://master.php.net/note/delete/99287/bad+code
Del: spam -- https://master.php.net/note/delete/99287/spam
Del: non-english -- https://master.php.net/note/delete/99287/non-english
Del: in docs -- https://master.php.net/note/delete/99287/in+docs
Del: other reasons-- https://master.php.net/note/delete/99287
Reject -- https://master.php.net/note/reject/99287
Search -- https://master.php.net/manage/user-notes.php