Re: __toString(), __toArray()

From: Date: Tue, 12 Jan 2010 03:17:53 +0000
Subject: Re: __toString(), __toArray()
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-46650@lists.php.net to get a copy of this message
Etienne Kneuss wrote:
Hello, On Mon, Jan 11, 2010 at 7:31 PM, Clint Priest <cpriest@warpmail.net> wrote:
I know there's been requests to add a __toArray() and most of the arguments against it is that there are too many magic functions already. I just thought I'd propose an alternative that would satisfy all of them. Why not a __cast($Type) magic function?
I'd advance two reasons against this idea: 1) It's more self-explanatory to explicitly call the appropriate converting method, enough with implicit madness! 2) For some operations, you'd have to know the types in advance before knowing what operations needs to be performed: $obj1 + 2; Now what __cast should be called? Int? Float?
Wouldn't it make sense to be an integer since its being added to an integer?
Also, what about $obj1 + $obj2: Int? Float? Array?
This is where operator over-loading would be useful however perhaps only explicit casts would make sense here.
Another example: str_replace($obj1, "bar", "foo"); what to call? __toString or __toArray? str_replace accepts both.
This is an interesting situation, could be resolved by attempting a __cast('array') followed by a __cast('string') if the first call was rejected (false, exception or something).
IMHO it would only make sense to invoke methods on explicit casts only, otherwise it will just be a mess with PHP's current type juggling. But, as we seen with __toString, limiting the field of application was annoying (and it was later extended to nearly all string usages).
I would agree with this as well, only called during explicit casts.
So, what will it be? Inconsistent and Confusing or Limited and Annoying?
One other alternative, probably not as easy would be to pass multiple types to cast, much the way the Accepts: HTTP header does, providing a list of possible cast types, in the preferred order. One could even implement an interface such as: interface Castable { function GetCastableTypes(); } or some such.
-- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php


« previous php.internals (#46650) next »