overloading - php overload equals-operator -


in php program have array of custom objects, , want find if array contains object. of course can use array_search, checks if objects same object, not if has same variables. want able create own compare function objects, can use array_search method (or similar). want able this:

class foo {     public $_a,$_b;     function __construct($a,$b)     {         $this->_a = $a;         $this->_b = $b;     }      function __equals($object)     {         return $this->_a == $object->_a;     } } $f1 = new foo(5,4); $f2 = new foo(4,6); $f3 = new foo(4,5);  $array = array($f1,$f2); $idx = array_search($f3,$array); // return 0 

is possible? know can create own array_search method uses method class, i'd have use 2 different search functions, 1 classes have own compare function, , 1 haven't.

here's neat little trick found out:

class foo {     public $a;     public $b;      public function __tostring() {         return (string)$this->a;     }      public function __construct($a, $b) {          $this->a = $a;          $this->b = $b;     }  }  $a = new foo(1, 'a'); $b = new foo(2, 'b'); $c = new foo(3, 'c'); $d = new foo(2, 'd'); $array = array($a, $b);  $key = array_search($d, $array);         // false  $key = array_search((string)$c, $array); // false $key = array_search((string)$d, $array); // 1 

this works:

$is_equal = ((string)$d == $b);          // true 

when passed string $needle, array_search try cast objects contained in $haystack string compare them, calling __tostring magic method if exists, in case returns foo::$a.


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -