Re: [RFC][VOTE] Objects as Keys
| From: | Rowan Collins | Date: | Wed, 17 Dec 2014 11:19:19 +0000 |
| Subject: | Re: [RFC][VOTE] Objects as Keys | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-79772@lists.php.net to get a copy of this message | ||
Stanislav Malyshev wrote on 17/12/2014 02:14:
No, it's not possible. It is possible to call object method in an expression, and then use the result of the expression as an array key. But to do that you'd have to check that you're dealing with the object and the call the special method.I think what Christoph was getting at is that you could implement an object map pretty simply by requiring the objects being added to implement a particular interface, as in: ... function add ( Hashable $obj ) {
$this->data[ $obj->getHash() ] = $obj;} ... The main thing that the current RFC would simplify is being able to accept a mixture of objects and scalars without performing an extra check; currently, you'd have to write something like this: ... function add ( $scalar_or_obj ) {
if ( is_scalar($scalar_or_obj) ) {
$this->data[ $scalar_or_obj ] = $scalar_or_obj;
} elseif ( $scalar_or_obj instanceOf Hashable ) {
$this->data[ $obj->getHash() ] = $obj;
} else {
throw new InvalidArgumentException;
}
}
...
Which is certainly uglier, any maybe was the case that Guilherme had in mind, but it's not like you have to build a whole new type of data structure, just add a few lines of implementation.
Compare that to trying to store the actual objects as keys, which would require a lot more than a few lines of code to emulate in pure PHP. Luckily, we have SplObjectStorage, which maybe makes that rather less urgent as well.
Regards,
--
Rowan Collins
[IMSoP]