Re: [PHP-DEV] Operator overloading for userspace objects

This is only part of a thread. view whole thread
February 6, 2020 20:06 (Andrea Faulds)

Nikita Popov wrote:
> Yes, i don't think it makes sense to group these operations in interfaces, > the use-cases are just too diverse. It's possible to define one interface > per operator (e.g. what Rust does), though I don't think this is going to > be particularly useful in PHP. I would not want to see functions accepting > int|float|(Add&Mul) show up, because someone is trying to be overly generic > in their interfaces ;)
The use-cases being diverse can be an argument against being able to overload individual operators — if you consider using, for example, + to mean something other than addition to be an issue. I don't like what happens in languages like C++ where you do a bitwise left-shift to output to a stream or divide two strings to concatenate paths. Haskell has a nice approach (probably some other languages have this too) where it has typeclasses that contain related operators, which means that e.g. if you want to overload +, your type needs to support Num which also contains -, *, abs, the sign function, and conversion from integers. The obvious translation to PHP would be to use interfaces with related operations grouped. We could even support overloading some of the maths functions in theory (whether we should, I don't know…) Of course, some determined person will just implement * because it's cool and throw exceptions in the other methods… Also, Haskell also lets you just define arbitrary operators, which may even look the same as the built-in ones if you really want to, so maybe it's a bad comparison point :p Andrea