[Concept] Magic Casting

From: Date: Fri, 02 Dec 2016 13:37:20 +0000
Subject: [Concept] Magic Casting
Groups: php.internals 
Request: Send a blank email to internals+get-97246@lists.php.net to get a copy of this message
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. An idea of how this may look would be: <?php class Collection extends ... { protected $items; public function __construct(array $items) { $this->items = $items; } ... public function __cast(array $items) : Collection { return new static($items) } } -- The __cast method MUST return an instance of itself, so that when called like so: function convert_me(Collection $collection) { var_dump($collection); } convert_me([1,2,3]); the result there would be a Collection instance, instead of an array. If the type passed is not accepted by __cast() or __cast() throws an exception, then the current errors of invalid type are thrown, or perhaps the custom exception message. I'm not sure if this has been proposed before, and if it has, please could someone assist in me finding it, I couldn't find it by a quick search on the wiki.php.net/rfc page. Thanks. Alex.

« previous php.internals (#97246) next »