note 117567 added to class.arrayaccess
| From: | kaRemovTihsjouniatgmAndTihsaildotcom | Date: | Tue, 30 Jun 2015 15:03:34 +0000 |
| Subject: | note 117567 added to class.arrayaccess | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-202998@lists.php.net to get a copy of this message | ||
reset() method may not work as you expect with ArrayAccess objects.
Using reset($myArrayAccessObject) returns the first property from $myArrayAccessObject, not the
first item in the items array.
If you want to use the reset() method to return the first array item, then you can use the following
simple workaround:
<?php
class MyArrayAccessObject implements Iterator, ArrayAccess, Countable {
protected $first = null; //WARNING! Keep this always first.
protected $items = null;
private function supportReset() {
$this->first = reset($this->items); //Support reset().
}
// ...
public function offsetSet($offset, $value) {
if ($offset === null) {
$this->items[] = $value;
}
else {
$this->items[$offset] = $value;
}
$this->supportReset();
}
}
?>
Finally, call $this->supportReset() in the end of all methods that change the internal $items
array, such as in offsetSet(), offsetUnset() etc.
This way, you can use the reset() method as normally:
<?php
$firstArrayItem = reset($myArrayAccessObject);
?>
----
Server IP: 72.52.91.14
Probable Submitter: 88.86.155.34
----
Manual Page -- http://php.net/manual/en/class.arrayaccess.php
Edit -- https://master.php.net/note/edit/117567
Del: integrated -- https://master.php.net/note/delete/117567/integrated
Del: useless -- https://master.php.net/note/delete/117567/useless
Del: bad code -- https://master.php.net/note/delete/117567/bad+code
Del: spam -- https://master.php.net/note/delete/117567/spam
Del: non-english -- https://master.php.net/note/delete/117567/non-english
Del: in docs -- https://master.php.net/note/delete/117567/in+docs
Del: other reasons-- https://master.php.net/note/delete/117567
Reject -- https://master.php.net/note/reject/117567
Search -- https://master.php.net/manage/user-notes.php