> I'm personally unconvinced of the value of this, and would probably propose
> it was blocked by coding standards in my team if it was added, because its
> meaning is so ambiguous.

That's perfectly reasonable. Do you also block use of casting to a string with 
(string) $foo as well? I ask because this proposal is simply on par with the 
idea behind string casting for objects. 

I don't expect that everyone would use custom array casting via __toArray(), 
but for those that would like to have that control and ease of use, it'd be 
valuable for them.

> I actually see quite a lot of classes with normal methods called things
> like "toArray", and my comment is always "to *what* array?" Most objects do
> not have a single "natural"/"canonical" array representation

I think the same could be said about "__toString()". But with that, some 
classes can be boiled down to a single representation, such as the Ramsey\Uuid 
<https://github.com/ramsey/uuid/> package. The same is with arrays. You can 
have a single entity such as person to where its array representation can be 
first name, last name, age, race, gender, email, etc..., or you can have a 
collection of items, to where in that representation as an array, you have 
control over what information is returned and what isn't.

> As a thought experiment, imagine a similar method which allowed you to
> overload (object)$foo. Although (array)$foo tells you slightly more than
> that, I'm not convinced it tells you enough that you're not just hiding
> meaning behind cute syntax.

I'm confused by example, as there's no real need to overload casting to an 
object as a class is already an object. Whereas, a class is not already an 
array. It's not about "cute syntax", it's honestly about providing a simple 
clutter free helper for developers to take control over how their classes are 
transformed to array representations.

> JsonSerializable actually suffers from similar problems, and is IMO useful
> only because it's automatically recursive. I presume the proposed mechanism
> would not be, i.e. return [$foo] would not be interpreted as return
> [(array)$foo].

You bring up a good point. Could you for a moment pretend like you're behind 
this proposal and expand upon this question? If PHP were to have a __toArray() 
method, would you see it as being recursive? In your opinion, how should/would 
it react?

I know not everyone will want or use this feature, but for those who would, 
it'd be a great addition IMO. So my goal of this initial thread was to see, 
"what if we had this feature, what would we want it to do?", and go from there.

--
Steven Wade
stevenwad...@gmail.com



Reply via email to