On Wed, 2014-09-24 at 20:45 +0100, Andrea Faulds wrote:
> On 24 Sep 2014, at 13:24, Johannes Schlüter <[email protected]> wrote:
>
> > Taking this sample code:::
> >
> > <?php
> > class C {
> > function __toString() {
> > return "C";
> > }
> > }
> >
> > $a = [];
> >
> > $c1 = new C();
> > $c2 = new C();
> >
> > $a[$c1] = 23;
> > $a[$c2] = 42;
> > ?>
> >
> > 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.
>
> I’m not sure this is a fair example. Don’t classes usually implement a
> `__toString()` that is based on the data they contain? If they don’t,
> I’m not sure they’re useful for indexing anyway.
"Usually" is a bad term - we have no idea what >99% of our suers do ;)
I don't think there is a clear leader on usage of __toString(), for some
it is a debugging feature, for some a "normal" operation.
The interesting question are value objects
<?php
$a = new DateTime("2014-09-24");
$b = new DateTime("2014-09-24");
$c = $a;
$d = [];
$d[$a]++;
$d[$b]++;
$d[$c]++;
?>
We can define we're using object identity as I did above or we add a
__hash() method, which again is more magic.
Last time this was discussed the magic didn't win and therefore having
objects as keys is forbidden so the user has to decide on
hashing/identifying himself in an explicit way.
johannes
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php