DEV Community

Aju Chacko
Aju Chacko

Posted on

1 1

php RFC:__toArray()

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"
 ]
*/
Enter fullscreen mode Exit fullscreen mode

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"
}
*/
Enter fullscreen mode Exit fullscreen mode
function bar(Person $person): array {
    return $person;
}

print_r(bar($person));

// Output
/*
[
  "name" =>"John Doe"
  "email"=>"jon@example.com"
]
*/
Enter fullscreen mode Exit fullscreen mode
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.
Enter fullscreen mode Exit fullscreen mode

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

AWS Security LIVE! Stream

Go beyond the firewall

Watch AWS Security LIVE! to uncover how today’s cybersecurity teams secure what matters most.

Learn More

Top comments (0)

Image of PulumiUP 2025

Let's talk about the current state of cloud and IaC, platform engineering, and security.

Dive into the stories and experiences of innovators and experts, from Startup Founders to Industry Leaders at PulumiUP 2025.

Register Now

👋 Kindness is contagious

Value this insightful article and join the thriving DEV Community. Developers of every skill level are encouraged to contribute and expand our collective knowledge.

A simple “thank you” can uplift someone’s spirits. Leave your appreciation in the comments!

On DEV, exchanging expertise lightens our path and reinforces our bonds. Enjoyed the read? A quick note of thanks to the author means a lot.

Okay