php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #25772 Custom comparison of objects: __equals method
Submitted: 2003-10-07 04:05 UTC Modified: 2004-04-15 03:29 UTC
Votes:12
Avg. Score:4.6 ± 0.8
Reproduced:10 of 10 (100.0%)
Same Version:2 (20.0%)
Same OS:5 (50.0%)
From: dmitrijsl at swh-t dot lv Assigned:
Status: Wont fix Package: Feature/Change Request
PHP Version: 5.0.0b1 (beta1) OS: *
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2003-10-07 04:05 UTC] dmitrijsl at swh-t dot lv
Description:
------------
If a class defines a __equals($other) function, invoke that function on object comparison. Example:

==========================
class MyClass {
    public function __construct($value) {
        $this->value = $value;
    }

    /**
     * This function should be invoked on object
     * comparison with == or != operators.
     */
    public function __equals($other) {
        if ($other instanceof MyClass) {
            return ((int)$this->value
                   == (int)$other->value);
        } else {
            return false;
        }
    }

    private $value;
}

$a = new MyClass(3.14);
$b = new MyClass(3.13);

if ($a == $b) {
    echo '$a equals $b';
}
==========================

The comparison of $a and $b should result in the invokation of __equals function of MyClass. The same should apply to the != (not equals) operator.



Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2003-10-07 05:21 UTC] helly@php.net
If at all then we should be able to do all comparisons directly by __compare($other, $operator) where operator is one of {<,<=,==,!=,>,>=} or by another method __less() which performs a < test so that __less() and __equals() can be used to emulate all other tests.
 [2004-04-14 22:58 UTC] jevon at jevon dot org
Would love this feature! Java implements this through:

class Object {
   boolean equals(Object o);
}

So you could either make all user-defined objects include a simple equals() function [and similarly, identical()].

Or perhaps, develop the aforementioned magic __equals() [and __identical()] functions. (As well as __less())
 [2004-04-15 03:29 UTC] derick@php.net
We're not going to have more magic then there already is; those things are going to be to complicated and confusing (See the __string()) issue.
 [2011-11-18 05:58 UTC] morrison dot levi at gmail dot com
I would like to know why this is so complicated and why it's marked as closed, 
won't fix.
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Thu Jan 17 05:01:25 2019 UTC