Req #49369 [Com]: Change current(), key(), next(), etc. to check for Iterator
| From: | tom at r dot je | Date: | Fri, 09 Dec 2016 12:32:57 +0000 |
| Subject: | Req #49369 [Com]: Change current(), key(), next(), etc. to check for Iterator | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-205877@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=49369&edit=1
ID: 49369
Comment by: tom at r dot je
Reported by: admin at ifyouwantblood dot de
Summary: Change current(), key(), next(), etc. to check for
Iterator
Status: Open
Type: Feature/Change Request
Package: Arrays related
Operating System: *
PHP Version: *
Block user comment: N
Private report: N
New Comment:
Now that in 7.1 we can type hint iterable this would be very useful.
function foo(iterable $i) {
$first = current($i);
$last = end($i);
}
Because $i is an iterator or an array, we can't differentiate between $i->current() and
current($i) we'd need to do:
function foo(iterable $i) {
if (is_array($i)) {
$first = current($i);
$last = end($i);
}
else if ($i instanceof Traversable) {
$first = $i->current();
foreach ($i as $x) {
$last = $x;
}
}
}
It would be a lot simpler if this logic was abstracted into the various functions so they can work
with either Traversable or array types.
Previous Comments:
------------------------------------------------------------------------
[2012-12-09 01:48:58] levim@php.net
Added bug #63678 as a duplicate.
------------------------------------------------------------------------
[2012-11-16 04:35:52] levim@php.net
Sorry, I misunderstood the bug. Silly me. Ignore my above comments.
------------------------------------------------------------------------
[2012-11-16 04:33:26] levim@php.net
Also, calling
current($i) gets the current value of the object $i which is
the
array; it doesn't call $i->current.
------------------------------------------------------------------------
[2012-11-16 04:27:19] levim@php.net
I'm not sure this is a php bug. Iterators should be rewound almost 100% of the
time before being used, especially when using an array or an object that
implements Iterator instead of IteratorAggregate.
Maybe the documentation should try to make this better known?
------------------------------------------------------------------------
[2012-07-01 11:14:30] bugs dot php dot net dot nsp at cvogt dot org
As a further note, the current behavior or current() also leaks private fields unlike e.g. http://php.net/manual/en/language.oop5.iterations.php.
class Test{
private $field = 5;
public $field3 = 6;
}
$t = new Test;
print current($t);
Expected result:
6
Actual result:
5
------------------------------------------------------------------------
The remainder of the comments for this report are too long. To view
the rest of the comments, please view the bug report online at
https://bugs.php.net/bug.php?id=49369
--
Edit this bug report at https://bugs.php.net/bug.php?id=49369&edit=1