This is a new RFC under discussion, proposed for php version 8. It is to add a new magic method called __toArray() to allow a class to control how it is represented when converted to an array.
class Person
{
protected $name;
protected $email;
public $another = 'value';
public function __construct(string $name, string $email)
{
$this->name = $name;
$this->email = $email;
}
public function __toArray()
{
return [
'name' => $this->name,
'email' => $this->email,
];
}
}
$person = new Person('John Doe', 'jon@example.com');
$personArray = (array) $person; // casting triggers __toArray()
# Result
/*
[
"name" => "John Doe",
"email" => "jon@example.com"
]
*/
Calling any objects implemented __toArray() magic method on any array context including type hinting(only when using weak typing) and return types can get array version of the object.
Usage
function foo(array $person) {
print_r($person);
}
// Output
/*
[
"name" => "John Doe"
"email"=> "jon@example.com"
}
*/
function bar(Person $person): array {
return $person;
}
print_r(bar($person));
// Output
/*
[
"name" =>"John Doe"
"email"=>"jon@example.com"
]
*/
declare(strict_types=1);
function bar(Person $person): array {
return (array) $person;
}
/*
[
"name" =>"John Doe"
"email"=>"jon@example.com"
]
*/
// Note: without the array type casting before return would trigger an error here.
This is similar to PHP's current implementation of __toString(),
a copy of the given object's value as an array
is made upon conversion.
However this proposal does not allow accessing and setting values as you would in a normal array, that functionality remains with classes implementing the ArrayAccess interface.
For more information take a look at the RFC
Top comments (0)