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

This is only part of a thread. view whole thread
January 31, 2020 16:35 (Benjamin Morel)
I like this whole operator overloading thing. I would probably use it in
brick/math <> and brick/money
<> to replace verbose `->plus()`,
`->multipliedBy()` etc. calls.

> Can you only compare 2 of the same type? What about subclasses? Can that differ if a subclass overrides that method? What happens to
commutativity then? Can you compare based on an interface? I think that this should behave exactly the same as if you replaced `$a + $b` with `$a->__add($b)` in your code. Nothing more, nothing less. The result will depend on whether you type-hinted your magic method or not.
> These operators only make sense on value objects, not service objects, and value objects should be immutable.
Indeed, we would need to make it clear that the operation must not modify the value of the current object, that should be effectively treated as immutable. Because it will probably be hard for the engine to enforce this, what about using the same convention I use in my libraries, i.e. `plus()` instead of `add()`, `dividedBy()` instead of `divide()`, etc.? This would translate to magic methods such as: __plus() __minus() __multipliedBy() __dividedBy() Benjamin