# Invokation on __toString() for object used as array key

- Thread: https://externals.io/message/77510
- Original archive: https://news-web.php.net/php.internals/77510
- Started by Nicolai Scheer on 2014-09-23T08:04:34+00:00
- Messages: 37
- Page 1 of 2: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/77510.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #77510 — Nicolai Scheer — 2014-09-23T08:04:34+00:00

URL: https://externals.io/message/77510#77510

Hi all,

until 5 minutes ago I thought it would be perfectly legal to use an object
as an array key, given that its __toString() method is in place.

Seems as if I was wrong.
I know that array keys are not what is considered "string context"
internally, at least not directly.

Would it harm in any way to add that feature?

Greetings

Nico

---

## #77514 — Michael Wallner — 2014-09-23T08:51:13+00:00

URL: https://externals.io/message/77510#77514 · In reply to: #77510

> Hi all,
> 
> until 5 minutes ago I thought it would be perfectly legal to use an object
> as an array key, given that its __toString() method is in place.
> 
> Seems as if I was wrong.
> I know that array keys are not what is considered "string context"
> internally, at least not directly.
> 
> Would it harm in any way to add that feature?

Yes, it was removed intentionally (quite a long time ago), like using
resources as array keys, to avoid hard-to-trace bugs for the user. At
least that's the reasoning I can remember.


-- 
Regards,
Mike

---

## #77516 — Leigh — 2014-09-23T09:15:28+00:00

URL: https://externals.io/message/77510#77516 · In reply to: #77514

>
> Yes, it was removed intentionally (quite a long time ago), like using
> resources as array keys, to avoid hard-to-trace bugs for the user. At
> least that's the reasoning I can remember.

He doesn't want to add the object as a key, he wants to invoke __toString().

Is there really any harm in adding a IS_OBJECT case to
zend_whatever_add_array_element, and checking if it has a __toString?

---

## #77518 — Andrea Faulds — 2014-09-23T09:29:45+00:00

URL: https://externals.io/message/77510#77518 · In reply to: #77516

> 
> 
> > […]
> 
> He doesn't want to add the object as a key, he wants to invoke __toString().
> 
> Is there really any harm in adding a IS_OBJECT case to
> zend_whatever_add_array_element, and checking if it has a __toString?
> 

It'd be great if, for the UString class krakjoe is working on, it could implicitly convert.

--
Andrea Faulds
http://ajf.me/

---

## #77519 — Andrey Andreev — 2014-09-23T09:34:26+00:00

URL: https://externals.io/message/77510#77519 · In reply to: #77518

>
> > […]

It does work if you do an explicit cast to string:

class Foo {
    public function __toString()
    {
        return 'Bar';
    }
}

$array = array();
$object = new Foo();
$array[(string) $object] = 'this works';

Cheers,
Andrey.

---

## #77520 — Michael Wallner — 2014-09-23T09:35:08+00:00

URL: https://externals.io/message/77510#77520 · In reply to: #77516

> 
> > […]
> 
> He doesn't want to add the object as a key, he wants to invoke __toString().

Did I write that?

> Is there really any harm in adding a IS_OBJECT case to
> zend_whatever_add_array_element, and checking if it has a __toString?

As already mentioned that behavior was intentionally removed.


-- 
Regards,
Mike

---

## #77521 — Leigh — 2014-09-23T09:45:26+00:00

URL: https://externals.io/message/77510#77521 · In reply to: #77520

> 
> > […]
>
> Did I write that?

No, you didn't, sorry.

I just didn't see how an object with an explicit method to convert it
to a string compared to using a resource straight up as a key. If you
were implying the resource would be cast to int, then I get the
comparison.

Does it really make bugs that hard to find? You'd expect the user to
know when they're using this behaviour when they write the code...
well, I would.

I suppose explicit casting removes any ambiguity, we use
$a[(int)$resource] all the time for arrays of sockets and that's
served us fine over the years. Hmm, thinking about it
$a[(string)$object] is a lot clearer than having some magic sort it
out. You're right, I'll retreat now :)

---

## #77522 — Michael Wallner — 2014-09-23T10:41:27+00:00

URL: https://externals.io/message/77510#77522 · In reply to: #77521

> 
> > […]
> 
> No, you didn't, sorry.
> 
> I just didn't see how an object with an explicit method to convert it
> to a string compared to using a resource straight up as a key. If you
> were implying the resource would be cast to int, then I get the
> comparison.
> 
> Does it really make bugs that hard to find? You'd expect the user to
> know when they're using this behaviour when they write the code...
> well, I would.
> 
> I suppose explicit casting removes any ambiguity, we use
> $a[(int)$resource] all the time for arrays of sockets and that's
> served us fine over the years. Hmm, thinking about it
> $a[(string)$object] is a lot clearer than having some magic sort it
> out. You're right, I'll retreat now :)
> 

I'm a "victim" of $array[(int) $resource] myself. I just tried to
explain that the behavior is intentional and not an oversight. That
doesn't mean that is set in stone for all times.

-- 
Regards,
Mike

---

## #77523 — Florian Margaine — 2014-09-23T10:53:31+00:00

URL: https://externals.io/message/77510#77523 · In reply to: #77522

Hi,

I do believe that the UString class would benefit from such a change.

Why would it be confusing to implement this?

Regards,

*Florian Margaine*
Le 23 sept. 2014 12:42, "Michael Wallner" <mike@php.net> a écrit :

> 
> > […]
> __toString().
> > […]
>
> I'm a "victim" of $array[(int) $resource] myself. I just tried to
> explain that the behavior is intentional and not an oversight. That
> doesn't mean that is set in stone for all times.
>
> --
> Regards,
> Mike

---

## #77559 — Stas Malyshev — 2014-09-24T00:08:32+00:00

URL: https://externals.io/message/77510#77559 · In reply to: #77523

Hi!

> I do believe that the UString class would benefit from such a change.
> 
> Why would it be confusing to implement this?

For some objects, it may lead to rather strange results - i.e.,
Exception has __toString() but probably not very useful one for use as
an array key. So may some other __toString methods. But in general, if
we streamline the conversion rules and set expectations, I don't see why
PHP engine can not check for object's convertor to string and even to
int if string one is not there. Yes, that would hide some errors but
also will enable some capabilities (like much smoother work with objects
that may simulate numbers, akin to GMP).

-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/

---

## #77566 — Michael Wallner — 2014-09-24T05:57:47+00:00

URL: https://externals.io/message/77510#77566 · In reply to: #77559

> Hi!
> 
> > […]
> 
> For some objects, it may lead to rather strange results - i.e.,
> Exception has __toString() but probably not very useful one for use as
> an array key. So may some other __toString methods. But in general, if
> we streamline the conversion rules and set expectations, I don't see why
> PHP engine can not check for object's convertor to string and even to
> int if string one is not there. Yes, that would hide some errors but
> also will enable some capabilities (like much smoother work with objects
> that may simulate numbers, akin to GMP).
> 

Well, then let's remove this restriction from resources, too.

-- 
Regards,
Mike

---

## #77568 — Stas Malyshev — 2014-09-24T06:30:33+00:00

URL: https://externals.io/message/77510#77568 · In reply to: #77566

Hi!

> Well, then let's remove this restriction from resources, too.

Not sure what use would it be for resources - resource IDs are not
controlled by user code and for all intents and purposes are opaque
numbers, which also do not have to be unique over the life of the
script. What use would it be to index by those, especially by implicit
convert? I don't think right now we have implicit convert of resources
to ints anywhere, like we do have with __toString.
-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/

---

## #77572 — Michael Wallner — 2014-09-24T08:19:36+00:00

URL: https://externals.io/message/77510#77572 · In reply to: #77568

> Hi!
> 
> > […]
> 
> Not sure what use would it be for resources - resource IDs are not
> controlled by user code and for all intents and purposes are opaque
> numbers, which also do not have to be unique over the life of the
> script. What use would it be to index by those, especially by implicit
> convert? I don't think right now we have implicit convert of resources
> to ints anywhere, like we do have with __toString.
> 

There's currently no way to associate any data with a resource, except
by its ID.

$context[(int) $resource] = ...;

IIRC resources *were* implicitely converted to integers up until a
specific version, I'll have to look that up in history, though.

-- 
Regards,
Mike

---

## #77573 — Pierre Joye — 2014-09-24T08:41:36+00:00

URL: https://externals.io/message/77510#77573 · In reply to: #77572

>
> 
> > […]
>
> There's currently no way to associate any data with a resource, except
> by its ID.
>
> $context[(int) $resource] = ...;
>
> IIRC resources *were* implicitely converted to integers up until a
> specific version, I'll have to look that up in history, though.
>

I also wonder why we still need them. Doing what has been done with gmp for
all resources would be a good move for 7.

---

## #77577 — johannes@schlueters.de — 2014-09-24T12:24:35+00:00

URL: https://externals.io/message/77510#77577 · In reply to: #77510

Hi,


> until 5 minutes ago I thought it would be perfectly legal to use an object
> as an array key, given that its __toString() method is in place.

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.


johannes

---

## #77586 — Stas Malyshev — 2014-09-24T19:39:50+00:00

URL: https://externals.io/message/77510#77586 · In reply to: #77573

Hi!

> I also wonder why we still need them. Doing what has been done with gmp
> for all resources would be a good move for 7.

In general, I think we do not - IIRC everything resources do objects can
do better now, and the problems that prevented one from using objects
instead of resources are long gone.

However, `is_resource()` checks and lots of third-party extensions using
resources may be a bit of a problem for eliminating them.
-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/

---

## #77587 — Andrea Faulds — 2014-09-24T19:44:10+00:00

URL: https://externals.io/message/77510#77587 · In reply to: #77586

> > […]
> 
> In general, I think we do not - IIRC everything resources do objects can
> do better now, and the problems that prevented one from using objects
> instead of resources are long gone.
> 
> However, `is_resource()` checks and lots of third-party extensions using
> resources may be a bit of a problem for eliminating them.

I already figured out how to solve the `is_resource()` issue. Create an almost-useless, uninstantiatable class called Resource which any new resource-replacing classes inherit from. Then, make `is_resource()` check whether something is an instance of that class.

Of course, 3rd-party extensions are still a problem, but this should mostly fix it. Of course, `gettype()` is still going to return “object” not “resource”, but I suspect people are more likely to use `is_resource()`.

--
Andrea Faulds
http://ajf.me/

---

## #77588 — Andrea Faulds — 2014-09-24T19:45:31+00:00

URL: https://externals.io/message/77510#77588 · In reply to: #77577

> 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.

--
Andrea Faulds
http://ajf.me/

---

## #77589 — Stas Malyshev — 2014-09-24T19:56:53+00:00

URL: https://externals.io/message/77510#77589 · In reply to: #77577

Hi!

> 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.
-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/

---

## #77590 — Stas Malyshev — 2014-09-24T19:59:42+00:00

URL: https://externals.io/message/77510#77590 · In reply to: #77587

Hi!

> I already figured out how to solve the `is_resource()` issue. Create
> an almost-useless, uninstantiatable class called Resource which any
> new resource-replacing classes inherit from. Then, make
> `is_resource()` check whether something is an instance of that
> class.

This is a nice idea, but maybe interface would be even better?

> Of course, 3rd-party extensions are still a problem, but this should
> mostly fix it. Of course, `gettype()` is still going to return “object”
> not “resource”, but I suspect people are more likely to use
> `is_resource()`.

yeah, I don't think I've seen many examples of something like checking
 `gettype()` of `fopen()` return. I've definitely seen checking it for
is_resource.

-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/

---

## #77591 — Andrea Faulds — 2014-09-24T20:01:09+00:00

URL: https://externals.io/message/77510#77591 · In reply to: #77589

> > […]
> 
> 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/

---

## #77592 — Stas Malyshev — 2014-09-24T20:08:48+00:00

URL: https://externals.io/message/77510#77592 · In reply to: #77591

Hi!

> 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) }

The hash doesn't have to be a nonsensical hex value, it can be something
like "My Object Number 42" if you want to. The difference is that
__toString is for human reading, and it's not always suitable for
hashing purposes. Just read the docs on any of the languages that have
separate hash method - they all have the same argument, there's a
different between printing an object for output and using the object as
a key.

> 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.

That's the point - it's not a cast. It's an operation that requires
object's identity. Again, given that so many languages have it, I don't
think it's really that weird. I think it's pretty natural.

> 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.

The problem is you mix here two completely different domains. On one
hand, you may want the object to have text representation for output
purposes - say, XML object would have XML output as it's string rep. On
other hand, I don't think you want to use 100K XML as a key, because
using as a key is a completely different issue. Converting to string is
a hack that mixes two different problems into one method, and that's why
it will lead to problems. The solution for this problem is known and
widely used - have a separate hash method. With PHP, you can actually
have a luxury of using a human-readable keys while still keeping them
nice and clean and independent from string representation. And if you
want maximum efficiency, you could switch to ints instead.
-- 
Stanislav Malyshev, Software Architect
SugarCRM: http://www.sugarcrm.com/

---

## #77593 — Andrea Faulds — 2014-09-24T20:12:55+00:00

URL: https://externals.io/message/77510#77593 · In reply to: #77592

> The hash doesn't have to be a nonsensical hex value, it can be something
> like "My Object Number 42" if you want to. The difference is that
> __toString is for human reading, and it's not always suitable for
> hashing purposes. Just read the docs on any of the languages that have
> separate hash method - they all have the same argument, there's a
> different between printing an object for output and using the object as
> a key.

Actually, yeah, I see your point. I suggest this, then:

    public function __toKey() : int | string {}

Psuedo-code, since you can’t have multiple return types. I think it’s a better name than __hash (fits well with __toString IMO), and this way we can support integer keys too, where that makes sense.
--
Andrea Faulds
http://ajf.me/

---

## #77594 — johannes@schlueters.de — 2014-09-24T20:46:36+00:00

URL: https://externals.io/message/77510#77594 · In reply to: #77588

> 
> 
> > […]
> 
> 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

---

## #77596 — Andrea Faulds — 2014-09-24T21:21:12+00:00

URL: https://externals.io/message/77510#77596 · In reply to: #77594

> 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.

If people want debugging, there is a method specifically for that, __debugInfo.

--
Andrea Faulds
http://ajf.me/

---

Next page: https://externals.io/message/77510.md?page=2
