On 2 December 2016 13:37:20 GMT+00:00, Alex Bowers <bowersb...@gmail.com> wrote: >Hello All, > >In PHP we currently have the ability to type hint classes in method >signatures, however, sometimes it would be useful to convert the items >to a >different instance / type. > >An example is collections and arrays. If implemented properly, an array >and >a collection could be used interchangeably, although a collection may >be >preferred. For consistency, having the ability to dynamically cast from >an >array to a collection would be very useful.
I think there are really two different features wrapped up here. First, allowing user defined classes to define casting behaviour to or from other types. This has certainly been discussed in different forms over the years, although mostly in terms of casting *to* another type (e.g. a generalisation of __toString). One of the big challenges is that without method overloading, how do you nicely declare two different casts, to or from different types? The generalised case also suffers from the problem of multiple despatch - do you call Foo::fromBar() or Bar::toFoo()? The second part is making that casting automatic when a type hint is encountered. I can sort of understand this as a generalisation of coercive type hints on scalars, but it feels like it could get rather hard to debug. It seems easier to read in your example to just type hint the collection, and make the user manually create one: function whatever(Collection $c) { ... } $a = array( ... ); whatever( Collection::fromArray($a) ); Explicit casts would take you from there to: function whatever(Collection $c) { ... } $a = array( ... ); whatever( (Collection)$a ); Either of these is more typing than the cast being implicitly added by the engine, but it's clearer that there's some conversion happening. Imagine if the cast is an expensive operation - calling it explicitly over and over again would be an obvious clue to refactor, but having it silently called repeatedly might go unnoticed. Regards, -- Rowan Collins [IMSoP] -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php