Re: Missing __toString() part
| From: | Adam Maccabee Trachtenberg | Date: | Mon, 05 Jun 2006 00:16:39 +0000 |
| Subject: | Re: Missing __toString() part | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-23947@lists.php.net to get a copy of this message | ||
On Sun, 4 Jun 2006, Andrei Zmievski wrote:
> I am sorry if I missed the whole thread. I think that using the
> result of __toString() for indexing objects is a bad idea. If we want
> to allow this behavior (which is actually useful in some situations),
> I'd rather we had a __hash() method or something similar to what
> Python does. The string representation of the object and its hashed
> representation may be very different.
After sitting on the fence on this one for a few days, I agree with
Andrei.
For example, for an eBay Item object, my __toString() returns the
Title, but that's not unique, so my __toHash() returns the numeric ID,
which is.
Furthermore, if my __toString() was unique, and I was relying on that
for keys in an array, I would have to mark that method as final;
otherwise, someone might unknowingly destroy the uniqueness in a child
class and break my code. That's not ideal because there could
otherwise be many good reasons that someone would want to override
__toString().
In contrast, it's unlikely that you would override __toHash(), and
it's pretty obvious that you shouldn't do something that could cause
collisions.
The other proposal, where PHP generates a unique object id, would also
be fine. Even better, perhaps. I'm not sure what I think yet.
-adam
--
adam@trachtenberg.com | http://www.trachtenberg.com
author of o'reilly's "upgrading to php 5" and "php cookbook"
avoid the holiday rush, buy your copies today!