note 100649 added to functions.anonymous
| From: | Anonymous at osu1 dot php dot net | Date: | Thu, 28 Oct 2010 07:54:33 +0000 |
| Subject: | note 100649 added to functions.anonymous | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-173544@lists.php.net to get a copy of this message | ||
use() parameters are early binding - they use the variable's value at the point where the
lambda function is declared, rather than the point where the lambda function is called (late
binding).
If you want late binding put & before the variable inside use()
<?php
$fn = function () use (&$var) { echo $var; };
?>
Examples:
<?php
// problem 1: this should echo "Canada", not a php notice
$fn = function () use ($country) { echo $country . "\n"; };
$country = 'Canada';
$fn();
// problem 2: this should echo "Canada", not "UnitedStates"
$country = 'UnitedStates';
$fn = function () use ($country) { echo $country . "\n"; };
$country = 'Canada';
$fn();
// problem 3: this should echo "Canada", not "UnitedStates"
$country = (object)array('name' => 'UnitedStates');
$fn = function () use ($country) { echo $country->name . "\n"; };
$country = (object)array('name' => 'Canada');
$fn();
// problem 4: this outputs "Canada". if this outputs "Canada",
// then so should problem 2 above. otherwise this should be
// just as broken as problem 2 and be outputting "UnitedStates"
$country = (object)array('name' => 'UnitedStates');
$fn = function () use ($country) { echo $country->name . "\n"; };
$country->name = 'Canada';
$fn();
?>
see http://bugs.php.net/bug.php?id=50980
(I've just quoted from there, but if you want you can read there the whole feature request)
----
Server IP: 69.147.83.197
Probable Submitter: 192.118.11.111
----
Manual Page -- http://www.php.net/manual/en/functions.anonymous.php
Edit -- https://master.php.net/note/edit/100649
Del: integrated -- https://master.php.net/note/delete/100649/integrated
Del: useless -- https://master.php.net/note/delete/100649/useless
Del: bad code -- https://master.php.net/note/delete/100649/bad+code
Del: spam -- https://master.php.net/note/delete/100649/spam
Del: non-english -- https://master.php.net/note/delete/100649/non-english
Del: in docs -- https://master.php.net/note/delete/100649/in+docs
Del: other reasons-- https://master.php.net/note/delete/100649
Reject -- https://master.php.net/note/reject/100649
Search -- https://master.php.net/manage/user-notes.php