On 28.03.2020 at 14:29, Andrea Faulds wrote:

> Christoph M. Becker wrote:
>
>> This "try left/right" approach is how operator overloading works for
>> internal classes[1], and apparently, it works quite well, as long as it
>> is not overused.
>
> I think “as long as it is not overused” are the key words there. We have
> a very limited number of internal classes with operator overloading
> right now, and the authors know about what other such classes exist and
> therefore can design with them in mind. But once any userland PHP class
> can use operator overloading, you could start seeing uses of operators
> where the left- and right-hand side are classes from unrelated libraries
> whose authors were not aware of eachother, and that could create strange
> problems when one or the other library is updated with operator overload
> handling.
>
> Consider Arnold's example:
>
>     $a + $b + $c - $d
>
> We are not constraining operator overloading to just be for number-like
> objects, it can in principle be used for absolutely anything.

And floats can be used to store monetary values, and to do calculations,
and apparently, that is actually done by some.  Was it a bad idea to
introduce floats to the language?

> $a here
> might have an overload that works for any right-hand-side object, but
> then once $b adds its own similar overload in a new version, the code no
> longer does the same thing when it's flipped around ($b + $a), violating
> the normal expectation that `+` is commutative, and that's before
> considering what $c and $d might do!

If, for example, the + operator is overloaded to add something to a
collection, the normal expectation that + is commutative is already
violated.  Operator overloading should definitely not be used for
"anything", but only for those rare cases which resemble math operations
(frankly, I would not have not supported __concat() at all).  Also,
overloaded operators should be programmed defensively, i.e. they should
not accept arbitrary arguments (how could that even work?), but only
those they can handle.  If implementations adhere to these "rules", I
don't see real issues.

--
Christoph M. Becker

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

Reply via email to