Edit report at http://bugs.php.net/bug.php?id=51875&edit=1

 ID:                 51875
 Comment by:         eric dot druid at gmail dot com
 Reported by:        dennis dot birkholz at nexxes dot net
 Summary:            Magic __compare() method for objects
 Status:             Open
 Type:               Feature/Change Request
 Package:            Class/Object related
 PHP Version:        Irrelevant
 Block user comment: N
 Private report:     N

 New Comment:

This is a duplicate of http://bugs.php.net/bug.php?id=25772


Previous Comments:
------------------------------------------------------------------------
[2010-05-20 22:06:41] dennis dot birkholz at nexxes dot net

Description:
------------
Objects can either be compared by checking if they are equivalent (are
references to the same object) or have the same values, which may lead
to severe performance penalties or recursion errors while checking. (See
http://de.php.net/manual/en/language.oop5.object-comparison.php)



When using database stored objects, the identifier for the object is
often stored as a single value within the object and it would be
sufficient to compare the IDs of two different objects to know if they
represent the same object in the database. In this cases, a ===
comparision would fail, the == comparison would succeed but could impose
large overhead if a lot of other objects are referenced within the
object. Sometimes even the == would fail because some caches are filled
in one instance but not in the other.



There are several thinkable possibilities to solve this problem:

1. Use a magic method __compare() that returns a token for the object
which then is used for comparison

2. Use a magic method __compare($obj) that returns true if the supplied
object matches the "questioned" object

3. Use a magic method __compare() that returns an array containing a
list of object properties to take into consideration, similar to the
__sleep() magic method.

Test script:
---------------
class A {

        protected $ID;

        public function __construct($id) { $this->ID = $id; }

        // Variant 1

        public function __compare() { return $this->ID; }

        

        // Variant 2

        public function __compare($obj) { return ($this->ID == $obj->ID); }

        

        // Variant 3

        public function __compare() { return array('ID'); }

}



$a1 = new A(10);

$a2 = new A(20);

$a3 = new A(10);



echo ($a1 === $a2 ? "YES" : "NO") . "\n";

echo ($a1 === $a3 ? "YES" : "NO") . "\n";



Expected result:
----------------
NO

YES



------------------------------------------------------------------------



-- 
Edit this bug report at http://bugs.php.net/bug.php?id=51875&edit=1

Reply via email to