php 重载等于运算符
在 PHP 程序中,我有一个包含一些自定义对象的数组,我想查找该数组是否包含某个对象。当然,我可以使用 array_search,但这会检查对象是否是同一对象,而不是它是否具有相同的变量。所以我希望能够为对象创建自己的比较函数,我可以将其与 array_search 方法(或类似的方法)一起使用。 我希望能够做这样的事情:
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
这样的事情可能吗? 我知道我也可以创建自己的 array_search 方法,该方法使用类中的方法,但是我必须使用 2 个不同的搜索函数,一个用于具有自己的比较函数的类,另一个用于那些没有自己的比较函数的类t。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是我最近发现的一个巧妙的小技巧:
这也有效:
当传递字符串 $needle 时,
array_search
将尝试转换 $haystack< 中包含的对象/em> 到字符串进行比较,方法是调用 __toString 魔术方法(如果存在),在本例中返回 Foo::$a。Here's a neat little trick I recently found out:
This also works:
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 returnsFoo::$a
.通常情况下不是。您可以查看 PECL Operators-Extension,但那确实很旧。
Usually its not. You may look at the PECL Operators-Extension, but thats really old.