Re: Concept: "arrayable" pseudo type and \Arrayable interface

From: Date: Tue, 19 Nov 2019 20:20:20 +0000
Subject: Re: Concept: "arrayable" pseudo type and \Arrayable interface
References: 1 2 3 4 5 6 7 8 9 10 11 12  Groups: php.internals 
Request: Send a blank email to internals+get-107838@lists.php.net to get a copy of this message
On Tue, Nov 19, 2019, at 9:54 AM, Rowan Tommins wrote: > Yes, I would see that as a better example. I think operator overloading in > general makes sense when the object itself can be thought of as a > special-case of the primitive it's emulating operators for. So in this > case, the IsSuccessful class would be "a special kind of boolean"; and the > hypothetical List or Collection classes I mentioned a couple of days ago > would be "a special kind of array". We even have that in PHP for built-in > types: GMP objects can now be used with mathematical operators like $foo * > $bar, and those operations do what you'd expect them to do on an integer or > float. > > Operator overloading can also be used just as a cute way of spelling > something - probably most famously, C++ uses the << and >> operators for > writing to and reading from streams, even though they're actually overloads > of the bit-shift operator. This kind of use is, I would say, more > controversial - going back to consistency, it's easier to reason about code > if $foo * $bar always does some kind of multiplication than if it's been > overloaded to mean "$foo is the star of $bar". > > Overloading of cast operators is no different - the clearest use cases for > __toString() are where the whole class basically represents a piece of > text, and the more controversial are where (string)$foo is actually a cute > spelling of one method on a complex class. I just want to pop in here to highlight this last point, because that's the best heuristic I've seen for when __toString() is appropriate or not. I may have to steal that heuristic because it's spot on. To the rest of the thread, I think it's wise to split discussion of __toArray() off from "arrayable". They seem like they are addressing different if related problems. While an object with __toArray() would be "arrayable", there's already 2 array-ish things: arrays and the ArrayAccess interface. So some short hand for array|\ArrayAccess can stand on its own as a proposal. Or, since we now have union types, maybe that makes such a shorthand no longer necessary. I'm not sure there. --Larry Garfield

« previous php.internals (#107838) next »