What happens if I perform array-like operations on an object implementing __toArray() from this RFC?

For example:

$obj["foo"] = 42;

or:

$bar = $obj["foo"];

(Imagine these examples are perhaps within a loop iterating a collection of objects)

Which operations do and do not work? As they'd be operating on a new from-cast array, I assume they would not be able to effect the original object (properties), but is this what people expect?

What I'm trying to get at here is: Does this RFC create opportunities for bugs arising because objects are accidentally treated as arrays and users would no longer receive any kind of warning or error from such code when they would have in the past?

(Aside: Could this get even more interesting where a loop involving references being (ab)used is involved? Experienced developers know you should avoid references, but many newer developers use them - either through misunderstanding the language or copying others and not actually understanding what they're doing. While, anecdotally from helping others in various channels, this occurs less than it did in the PHP 5 era, it does still occur.)

If so, I believe this is obviously bad. If not, I believe this is also bad because the above example do not work as someone (particularly newer users) might expect. The language is creating something which sometimes, maybe, acts like an array, but not always.


The other problem I have with this type of magic on objects is that people don't usually mean "to array", they mean "to array for specific purpose" - eg. "to array for database record" or "to array for API output". Using a magic method for this obfuscates the purpose of the returned array and could lead to problems, such as accidental data leakage, from cross-usage.

AllenJB


On 04/02/2020 13:03, Steven Wade wrote:
Hi all,

I’d like to officially open my __toArray() RFC <https://wiki.php.net/rfc/to-array> up 
to discussion. I’ve delayed changing the status until I had more time to respond to the 
discussion, but since it’s been brought up again 
<https://externals.io/message/108351>, I figured now is the best time.

https://wiki.php.net/rfc/to-array <https://wiki.php.net/rfc/to-array>

Cheers,

Steven Wade

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to