RE: [PHP-DEV] Proposal: interfaces for object to scalar type casting
| From: | François Laupretre | Date: | Wed, 13 May 2015 21:37:18 +0000 |
| Subject: | RE: [PHP-DEV] Proposal: interfaces for object to scalar type casting | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-86201@lists.php.net to get a copy of this message | ||
Hi,
> De : Guido Contreras Woda [mailto:guiwoda@gmail.com]
>
> Multiple frameworks and libraries define interfaces or objects that wrap
> around some scalar value and add behavior, the most common case being
> arrays and Collection / Hash[Set|List] objects. Although this objects
> benefit from the possibility of having behavior themselves, sometimes the
> implementation is outside our project scope (an external dependency) and
> interaction between this object and other blocks of code that expect scalar
> types usually needs to be controlled by the user, which adds the necessity
> for adapters or some sort of mediator.
>
> Now that we have the ability to hint return types, a common interface could
> be built that, given an object that implements it, lets userland code use
> this object as if it were the scalar type it is wrapping. Unboxing the
> object is pretty easy, and I wouldn't go as far as proposing interfaces for
> rebuilding the object itself (not now, at least).
>
> So, what do you think of a set of interfaces that allow userland objects to
> be used as scalar types?
First, we probably don't need anything for arrays. The Iterator interface family already
provides everything we need to consider an object as an array.
For other scalar types, while I agree casting should be supported, I don't like the solution of
creating new methods. I would prefer always calling __toString() and then, convert the string to the
desired type. So, (int)$object would just be a shortcut for (int)(string)$object. Quite easy to
implement, no new method, just need to enrich the convert_to_xxx() functions to go through
convert_to_string first. I already had this idea for 7.0 but missed time. Maybe for 7.1.
I also think it's more consistent as an object could not be transformed to different unrelated
values when cast to different scalar types. If $object, when cast to int, becomes 10 and, when cast
to string, becomes 'foo', is it consistent in such a loose typing system ? So, I prefer
that, by construction, (int)$obj always gives the same value as (int)(string)$obj.
Regards
François