> On Jul 1, 2015, at 2:25 PM, Anatol Belski <anatol....@belski.net> wrote:
> 
>> Expanding on this idea, a separate RFC could propose a magic
> __cast($value)
>> static method that would be called for code like below:
>> 
>> $obj = (ClassName) $scalarOrObject; // Invokes
>> ClassName::__cast($scalarOrObject);
>> 
>> This would allow UString to implement casting a string to a UString and
> allow
>> users to implement such behavior with their own classes.
>> 
>> However, I would not implement such casting syntax for UString only. Being
> able
>> to write $ustring = (UString) $string; without the ability to do so for
> other classes
>> would be unusual and confusing in my opinion. If an RFC adding such
> behavior
>> was implemented, UString could be updated to support casting.
>> 
>> Obviously a UString should be able to be cast to a scalar string using
> (string)
>> $ustring. If performance is a concern, UString::__toString() should cache
> the
>> result so multiple casts to the same object are quick.


> Hi,
> 
> One way doing this is already there thanks
> https://wiki.php.net/rfc/operator_overloading_gmp . Consider
> 
> $n = gmp_init(42); var_dump($n, (int)$n);
> 
> However the other way round - could be done on case by case basis, IMHO.
> Where it could make sense for class vs scalar, casting class to class is a
> quite unpredictable thing.
> 
> While users could implement it, how is it handled with arbitrary objects?
> How would it map properties, would those classes need to implement the same
> interface, et cetera? We're not in C at this point, where we would just
> force a block of memory to be interpreted as we want.
> 
> Regards
> 
> Anatol

Hello,

I was thinking that the __cast() static method would examine the parameter 
given, then use that value to build a new object and return it or return null 
(which would then result in the engine throwing an Error saying that 
$scalarOrValue could not be cast to ClassName). It was just a suggestion to see 
what others thought because someone suggested supporting casting syntax such as 
$ustring = (UString) $scalarString. I don’t really care for either method 
though (__cast() or enabling casting just for UString), as they don't offer any 
advantage over writing new UString($string) or UString::fromString($string).

Aaron Piotrowski
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to