PHP How to owerwrite object cast to array like: (array) $object with custom function


I need something like this:

class MyClass {
    $a = 'A';
    $b = 'B';
    public function __to_array(){
        $r = (array) $this;
        $r['ab'] = 'AB';
        return $r;

$x = new MyClass();

$x_as_array = (array) $x; 

In last line i need not return ['a'=>'A','b'=>'B'] but i need owerwrite this defaul cast to my custom __to_array function.




PHP doesn't have a native implementation of__toArray() like they do with__toString().

If you check out the PHP docs for converting to string, you'll see that the__toString() magic method is explicitly mentioned as a way to override the default implementation.

However, the documentation regarding type casting for arrays clearly states what happens when an object is converted to an array without mentioning any magic methods (emphasis mine)

Converting to array

For any of the types integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

If an object is converted to an array, the result is an array whose elements are the object's properties.....



The simple solution is to implement a->toArray() method in your class - something many popular collection implementations do (including Laravel's )

Another solution that may work is to have your class extend the class which allows objects to work as arrays.

People are also looking for solutions to the problem: php - How to implement array type route in Laravel?


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.