Re: Invokation on __toString() for object used as array key
| From: | Andrea Faulds | Date: | Wed, 24 Sep 2014 20:01:09 +0000 |
| Subject: | Re: Invokation on __toString() for object used as array key | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-77591@lists.php.net to get a copy of this message | ||
On 24 Sep 2014, at 20:56, Stas Malyshev <smalyshev@sugarcrm.com> wrote:
>> There the assumption would be that this leads to an array $a with two
>> elements, where in fact there is only one if __toString() is being
>> called. The only thing "making sense" would be using using the objects
>> identity (i.e. via spl_object_hash()) everything else leads to issues.
>
> This is a valid concern. For this, Java, for example, has separate
> methods hashCode() and toString(). Python has __str__, __repr__ and
> __hash__. Ruby has object.hash. So maybe we should have another magic,
> something like __hash(), that would produce a value for key? Then
> objects that implement __hash would be hashable and those that don't
> won't be, while still having usable __toString.
I’m not sure that’d make much sense. The object isn’t the key, the value the magic method
returns is. It would be quite odd to do this:
$someArray = [$my__hashImplementingObject => 1];
var_dump($someArray);
And see something like this, because we’ve called a hash function:
array(1) {
["ec10e5a66e281d105f302cacfb1aaca8"]=>
int(0)
}
I don’t really see what advantage this has over the normal __toString. Furthermore, having a
special method we use to cast here that’s used nowhere else seems weird.
Now, if we were to add actual object key support, that I might like. But if we’re going to keep
with just integers and strings, I’d much prefer to just support __toString here. I think users are
smart enough to understand that PHP arrays only have string or int keys, so it casts to a string.
--
Andrea Faulds
http://ajf.me/