|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2010-09-09 22:33 UTC] jtegwen at gmail dot com
Description:
------------
It would be nice to have an analogous method to __toString() for arrays.. maybe __toArray() for customized array return.
Test script:
---------------
class myObject {
private $data1;
private $data2;
private $meta1;
public function __construct($data1, $data2) {
$this->data1 = $data1;
$this->data2 = $data2;
$this->meta1 = strlen($data1) + strlen($data2);
}
public function __toArray() {
return array('data1'=>$this->data1, 'data2'=>$this->data2);
}
}
$obj = new myObject('test', 'script');
var_dump($obj);
Expected result:
----------------
array('data1'=>'test', 'data2'=> 'script')
Actual result:
--------------
Not implemented
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Mon Dec 08 02:00:01 2025 UTC |
I really think this is relevant. PHP 5.4 introduced something similar with the JsonSerializable interface. When you call json_encode on an object that implements it, it automatically calls the jsonSerialize() method that returns a string, an array, an integer, a float or a boolean. When you implement the jsonSerialize() method, you generally want to have a json-friendly representation of your current object, and you normally return an associative array with the properties you want to output. That looks like a __toArray() method, doesn't it ? What would be very nice is the following code to work : class A { protected $property1 = 'foo', $property2 = ['foo', 'bar'], $property3; public function __toArray() { return [ 'property1' => $this->property1, 'property2' => $this->property2, ]; } } class B { public static function doSomethingWithData(array $data) { // ... } } $a = new A; B::doSomethingWithData((array) $a); array_change_key_case($a, CASE_UPPER); // Would automatically cast $a to array and output ['PROPERTY1' => 'foo, 'PROPERTY2' => ['foo', 'bar']]