PHP 8.4.6 Released!

Voting

: three plus one?
(Example: nine)

The Note You're Voting On

kaRemovTihsjouni at gmAndTihsaildot com
9 years ago
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);
?>

<< Back to user notes page

AltStyle によって変換されたページ (->オリジナル) /