Re: Custom object equality
| From: | Lanre Waju | Date: | Wed, 18 Oct 2023 18:20:10 +0000 |
| Subject: | Re: Custom object equality | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-121418@lists.php.net to get a copy of this message | ||
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 aMoneyclass, which has anequals()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