|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull Requests |
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Sun Jan 11 20:00:01 2026 UTC |
Description: ------------ I am requesting other magic methods for automatic type conversion of objects, besides __toString(), in particular, __toArray(). The default method of converting an object to an array is, in my opinion, rather odd, since it provides the values of inaccessible properties and uses weird conventions, like an asterisk for protected properties and prefixing the class name for private properties. Test script: --------------- class Example { protected $a, $b, $c; public function __construct ($a) { $this->a = $a; $this->b = 'B'; $this->c = 'C'; } public function __toArray () { // Only return a and b, and don't distinguish scope return array ( 'a' => $this->a, 'b' => $this->b ); } } for ($examples = array (), $i = 0; $i < 3; $examples[] = (array) new Example(++$i)); echo json_encode($examples, JSON_PRETTY_PRINT); Expected result: ---------------- [ { "a": 1, "b": "B" }, { "a": 2, "b": "B" }, { "a": 3, "b": "B" } ]