Hello :-),
Casting is already a very large surface of unsafety and bugs. Adding
“magic” before this is like multiplying the surface by infinite.
The only goal I see here is to save a `new Collection(…)`, and this is
not a sufficient reason from my point of view. If `array` was a type,
and `IntoCollection` a trait, implemented for the `array` type, then we
could do things like `[1, 2, 3].intoCollection()` for instance. However
PHP does not bring this kind of features. So let's reverse this:
`Collection::fromArray([1, 2, 3])`. But wait, this is exactly what `new
Collection([1, 2, 3])` does for this specific case.
Do you have better use cases? A casting comes with a non-negligeable
cost. You have to define your data clearly, and avoid casting as much as
possible.
Cheers.
On 02.12.16 14:37, Alex Bowers 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.
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.
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php