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.

Reply via email to