duannaxin9975 2011-02-09 16:20
浏览 32
已采纳

php重载equals-operator

In a PHP program I have an array of some custom objects, and I want to find if the array contains a certain object. Of course I can use array_search, but this checks if the objects are the same object, not if it has the same variables. So I want to be able to create my own compare function for the objects, which I can use with the array_search method (or something similar). I want to be able to do something like 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 something like this possible? I know I can also create my own array_search method which uses a method from the class, but than I'd have to use 2 different search functions, one for the classes which do have their own compare function, and one for those which haven't.

  • 写回答

2条回答 默认 最新

  • doufu1950 2011-02-09 16:36
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题