On 11.09.2024 at 22:43, Hammed Ajao wrote: > Your point about operator overloading doesn't seem valid either. Consider > the following: > > ```php > class X { > public function plus(X $that) {} > public function equals(X $that) {} > } > ``` > > In this case, `plus` could represent any behavior, as could `equals`. If I > wanted to, I could implement `plus` to perform what `equals` does and vice > versa. Should we consider methods broken just because their names can be > arbitrary? > > PHP already distinguishes between comparison operators for objects: > > ```php > <?php > $obj1 = $obj2 = new stdclass; > assert($obj1 === $obj2); // compares object IDs > assert($obj1 == $obj2); // compares properties > $obj1 = new stdclass; > assert($obj1 !== $obj2); > assert($obj1 == $obj2); > ``` > > `===` compares object IDs, while `==` compares their properties. Beyond > this, there's little reason to apply an operator to an object directly. Why > would you need to call `$user1 + $user2` or similar operations on an > object? What scenario would break by allowing operator overloads? > > However, consider a case where comparing just one property of an object > (like a hash) is enough to determine equality. Wouldn't it be great if, > without changing any of the calling code, the engine compared `$this->hash > === $that->hash` when `$this == $that` is invoked, instead of all > properties? Without operator overloading, I'd have to define an `equals` > method and replace every `$obj == $x` call with `$obj->equals($x)`. > > Moreover, operator overloading unlocks new possibilities for algorithm > design. For example, you could define complex mathematical operations on > custom objects, enabling you to express algorithms more concisely and > naturally. Imagine implementing vector addition, matrix multiplication, or > symbolic computation directly in PHP. Instead of verbose method calls like > `$vec1->add($vec2)` or `$matrix1->multiply($matrix2)`, you could use simple > and intuitive syntax like `$vec1 + $vec2` or `$matrix1 * $matrix2`. This is > particularly useful for domain-specific algorithms where overloading > enhances readability and performance. > > Operator overloading isn't just about convenience. It opens the door to > more expressive algorithms, better readability, and reduces boilerplate > code, all while maintaining backward compatibility with existing PHP > behavior.
I fully agree, but note that at least two RFCs regarding userland operator overloading have been declined[1][2], and from what I remember at least partially because the feature could be "misused". [1] <https://wiki.php.net/rfc/user_defined_operator_overloads> [2] <https://wiki.php.net/rfc/userspace_operator_overloading> Christoph