I believe it's time to shift our focus away from backward compatibility
(BC) concerns in major versions. In my opinion, genuine operator
overloading is incomparable to the pseudo operator. I genuinely see the
operator overloads as an invaluable addition to PHP 9
Lanre
On 2023-10-18 6:50 a.m., someniatko wrote:
Hi internals,
There is often a need to compare whether two objects are equal. For
example, a popular [brick/money](https://packagist.org/packages/brick/money)
library has a `Money` class, which has an `equals()` method. However, this
becomes tedious to implement such methods, when multiple nested objects are
involved. For instance, Money has an amount and a currency.
There were already suggestions on the mailing list to allow "overloading"
existing `==` operator, and some suggestions went even as far as
overloading `<`, `>=` etc operators. However, overloading existing
operators may lead to a BC break between the PHP version which does support
the functionality, and which doesn't. It won't result in a BC break in case
it's an entirely new syntax, because a library or a project won't be able
to write code which overloads `==` in say PHP 8.4, but with code which
still works in PHP 8.3 - it will have to require PHP 8.4+. But if it is
implemented as a magic method, then `==` will work differently for 8.3 and
8.4.
I suggest thinking about introducing a new operator `~=`, which signifies
that custom equality is requested. In such a case, `==` will work as it
works now, and by default `~=` will work also like `==`, unless its
behavior is overwritten via a magic method. If a magic method is not
present in a class being compared, `~=` will compare two objects field by
field, but using `~=` comparison rather than `==` comparison, recursively.
For instance, a Money object may consist of Amount and Currency. If two
Moneys are compared using `~=`, and Money does not implement a magic
method, Amount also doesn't implement it, but Currency does, then Amounts
are compared using `~=` which is equal to `==` comparison in this case,
but Currencies are compared using their custom comparison logic.
This approach allows combining
- no BC break - `~=` is a new syntax which is unavailable in older PHP
versions
- explicitly showing an intent that objects are compared using a custom
comparison, rather than standard PHP one
- allow to skip writing boilerplate equals() methods which just forward
equals() to the nested objects
- standardize such comparisons on the language level
Of course how exactly this operator looks may be changed, `~=` is just an
example.
WDYT?
Regards,
Illia / someniatko
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php