php overload equals-operator php overload equals-operator php php

php overload equals-operator


Here's a neat little trick I recently 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 also works:

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

When passed a string $needle, array_search will try to cast the objects contained in $haystack to string to compare them, by calling the __toString magic method if it exists, which in this case returns Foo::$a.


Usually its not. You may look at the PECL Operators-Extension, but thats really old.