|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2011-09-07 02:45 UTC] xiezhenye at gmail dot com
Description:
------------
Closure use variable by ref not work with Iterator.
when use foreach on an Iterator used a Closure, the variable used by ref seems used by val.
Test script:
---------------
class OneWayIterator implements Iterator {
protected $end = false;
protected $getNext = null;
protected $value = null;
function __construct($next) {
$this->getNext = $next;
}
function current() {
return $this->value;
}
function next() {
try {
$this->value = call_user_func($this->getNext);
} catch (IteratorEndException $e) {
$this->end = true;
}
}
function key() {
}
function valid() {
return !$this->end;
}
function rewind() {
try {
$this->value = call_user_func($this->getNext);
} catch (IteratorEndException $e) {
$this->end = true;
}
}
}
class IteratorEndException extends Exception {
}
$i = 0;
$f = function() use (&$i) {
if ($i >= 10) {
throw new IteratorEndException();
}
return $i++;
};
foreach ($itr as $i) {
echo "$i\n";
}
Expected result:
----------------
0
1
2
3
4
5
6
7
8
9
Actual result:
--------------
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
...
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Dec 04 12:00:02 2025 UTC |
there is no "block scope" in php, you should use another variable name to make the test works "as expected", like: foreach ($itr as $mmm) { echo "$mmm\n"; } thanks