php - How to return special value when objected is casted to an array? -
there magic method __tostring
, triggered if object used in string context or casted such, e.g.
<?php class foo { public function __tostring() { return 'bar'; } } echo (string) new foo(); // return 'bar';
is there similar function triggered when object castend (array)
?
no, there arrayaccess
interface, allows use class array. looping functionality la foreach
need interface iteratoraggregate
or iterator
. former easier use if have internal array using because need override 1 method (which provides instance of arrayiterator
), latter allows more fine-grain control on iterating.
example:
class messages extends arrayaccess, iteratoraggregate { private $messages = array(); public function offsetexists($offset) { return array_key_exists($offset, $this->messages); } public function offsetget($offset) { return $this->messages[$offset]; } public function offsetset($offset, $value) { $this->messages[$offset] = $value; } public function offsetunset($offset) { unset($this->messages[$offset]); } public function getiterator() { return new arrayiterator($this->messages); } } $messages = new messages(); $messages[0] = 'abc'; echo $messages[0]; // 'abc' foreach($messages $message) { echo $message; } // 'abc'
Comments
Post a Comment