How to return a special value when an objected object is passed to an array?

There is a magic __toString method that will fire if an object is used in the context of a string or passed to one, for example

 <?php class Foo { public function __toString() { return 'bar'; } } echo (string) new Foo(); // return 'bar'; 

Is there a similar function that will fire when the object is displayed in (array) ?

+4
source share
2 answers

No, but there is an ArrayAccess interface that allows you to use the class as an array. To get a la foreach looping functions, you will need IteratorAggregate or Iterator . The former is easier to use if you have an internal array that you are using because you only need to override one method (which provides an ArrayIterator instance), but the latter allows you finer-grained control over the iteration.

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 as $message) { echo $message; } // 'abc' 
+2
source

This may not be exactly what you might have expected, because what you are expecting is not available as a PHP language function (unfortunately), but here comes a well-known workaround:

Use get_object_vars() for this:

 $f = new Foo(); var_dump(get_object_vars($f)); 

It will return an associative array with property names as indices and their values. Check out this example:

 class Foo { public $bar = 'hello world'; // even protected and private members will get exported: protected $test = 'I\'m protected'; private $test2 = 'I\'m private'; public function toArray() { return get_object_vars($this); } } $f = new Foo(); var_dump($f->toArray()); 

Output:

 array(2) { 'bar' => string(11) "hello world" 'test' => string(13) "I'm protected" 'test2' => string(13) "I'm private" } 
+2
source

Source: https://habr.com/ru/post/1479163/


All Articles