Casting object to array - any magic method being called? Casting object to array - any magic method being called? arrays arrays

Casting object to array - any magic method being called?


No

There is no __toArray magic method in PHP. An enhancement proposal has been rejected in 2006 with the following answer:

[2006-08-20 11:12 UTC] helly@php.net

Why not simply have a method asArray() maybe even as par of an interface:

interface ArrayConversion { function asArray(); }

See, we have __toString as it is supported in language constructs like echo, print and other internal functions. But we decided against an autoconversion for arrays already. So itwill never be supported in any language construct. That said there is no needed for this and nothing you would win against the above interface. In fact you would make it php more complex because you'd add just one more magic feature.

It is thus very unlikely that it will be implemented in any future release (which is a pity, if you ask me).


You can have the class implement the ArrayAccess interface. This will allow you to treat the object like an array without casting and you get total control over how the members are used.


Sadly no, casting to array doesn't trigger any magic method like it is done with:

$s = (string)$obj;

which triggers __toString() method and which you can override.

However, you may write a custom toArray() method.

You may also be interested in the Serializable interface which allows you to write custom serializer strategy.