在某些对象上调用时重载count()的行为 [英] Overload the behavior of count() when called on certain objects
问题描述
Possible Duplicate:
Count elements for objects implementing ArrayAccess using count()?
在PHP 5中,您可以使用魔术方法,重载某些类等.在C ++中,只要参数类型不同,就可以实现存在的函数.有没有办法在PHP中做到这一点?
In PHP 5, you can use magic methods, overload some classes, etc. In C++, you can implement functions that exist as long as the argument types are different. Is there a way to do this in PHP?
我想做的一个例子是:
class a {
function a() {
$this->list = array("1", "2");
}
}
$blah = new a();
count($blah);
我想返回2.IE计算类中特定数组的值.因此,在C ++中,我执行此操作的方式可能如下所示:
I would like blah to return 2. IE count the values of a specific array in the class. So in C++, the way I would do this might look like this:
int count(a varName) { return count(varName->list); }
基本上,我正在尝试简化大型应用程序的数据调用,因此我可以调用它:
Basically, I am trying to simplify data calls for a large application so I can call do this:
count($object);
而不是
count($object->list);
该列表将可能是对象列表,因此,取决于使用方式,如果有人必须以当前方式进行操作,这可能真是令人讨厌的声明:
The list is going to be potentially a list of objects so depending on how it's used, it could be really nasty statement if someone has to do it the current way:
count($object->list[0]->list[0]->list);
所以,我可以做些类似的事情吗
So, can I make something similar to this:
function count(a $object) {
count($object->list);
}
我知道PHP的计数接受混合的var,所以我不知道是否可以覆盖单个类型.
I know PHP's count accepts a mixed var, so I don't know if I can override an individual type.
推荐答案
听起来您想实现 Countable
接口:
It sounds like you want to implement the Countable
interface:
class a implements Countable {
public function __construct() {
$this->list = array("1", "2");
}
public function count() {
return count($this->list);
}
}
$blah = new a();
echo count($blah); // 2
这篇关于在某些对象上调用时重载count()的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!