Considering
this article proposes to add ArraySerializable interface and to allow the changing of existing array conversion mechanism. As an example of this change, consider the following code-snippet:
<?php
class Person implements ArraySerializable
{
public $name;
public $phone;
public function __toArray()
{
return array("name" => $this->name, "phone" => $phone);
}
}
class Phone implements ArraySerializable
{
public $number;
public function __toArray()
{
return array("number" => $this->number);
}
}
$person = new Person();
$person->name = "John";
$phone = new Phone();
$phone->number = "123456789";
$person->phone = $phone;
var_dump((array)$person);
# will outputs
#array(2) {
# ["name"]=>
# string(4) "John"
# ["phone"]=>
# object(Phone)#2 (1) { // oops, does not work recursively.
# ["number"]=>
# string(9) "123456789"
# }
#}
Currently, the above implicit object to array conversion does not work recursively. This propose changes object to array conversion behaviour which implements ArraySerializable interface. specifically ArraySerializable::__toArray method overrides current (array) cast.
<?php
interface ArraySerializable
{
/** @return array */
public function __toArray();
}
Usually, We serialise PHP object to some portable formats. At such a time as this. we define toArray()
method which decides what values are necessary to convert to array.
public function toArray()
{
$result = array();
foreach ($this as $key => $value) {
if (in_array($key, $this->whitelist()) {
if (is_object($value)) {
$result[$key] = $value->toArray();
} else {
$result[$key] = $value;
}
}
}
return $result;
}
We don't have common rule to convert to array from object.
ArraySerializable interface provides common way to convert to array from object. also impose conversion rule.
__toArray()
returning value excepts an array and It values only acceptsprimitive
type. (long, double, string and array)- do cast to array operation when the value contains object which implements ArraySerializable interface
- otherwise, raise RuntimeException.
__toArray()
method calls implicitly when cast to array from object.
__toArray
expects array cast operator. does not work correctly when call__toArray()
method manually.- specifically, children implicit conversion doesn't work. also it doesn't throw exception.
rough concept patch (for PHP_5.6 branch) is here: maybe i'll add ArraySerializable interface under Zend directory.