所以我正在使用一些我没有完整资源的外部PHP代码。我正在使用反射来计算可调用的方法等。
他们有这样的课程:
class SpecialArray implments \ArrayAccess
{
public function offsetExists($index){}
public function offsetGet($index){}
public function offsetSet($index, $value){}
public function offsetUnset($index){}
}
所以逻辑上我可以foreach(SpecialArray)
,那很好。
但是在代码中我可以某种方式count(SpecialArray)
并获得正确的计数,例如,如果SpecialArray中有5个元素,count(SpecialArray)
将返回5!
但是,类中没有count
方法,类也没有实现Countable
使用SpecialArray->count()
Call to undefined method
也失败了
有没有人有任何想法他们如何做这个伏都教魔术?
完整\ReflectionClass::export()
Class [ class ThirdParty\SpecialArray implements ArrayAccess ] {
- Constants [0] {
}
- Static properties [1] {
Property [ public static $_metadata ]
}
- Static methods [1] {
Method [ static public method &getMetadata ] {
- Parameters [0] {
}
}
}
- Properties [0] {
}
- Methods [5] {
Method [ public method offsetExists ] {
- Parameters [1] {
Parameter #0 [ $index ]
}
}
Method [ public method offsetGet ] {
- Parameters [1] {
Parameter #0 [ $index ]
}
}
Method [ public method offsetSet ] {
- Parameters [2] {
Parameter #0 [ $index ]
Parameter #1 [ $value ]
}
}
Method [ public method offsetUnset ] {
- Parameters [1] {
Parameter #0 [ $index ]
}
}
Method [ public method fetch ] {
- Parameters [1] {
Parameter #0 [ $index ]
}
}
}
}
答案 0 :(得分:2)
在测试代码之后,我得到了返回值1.让我引用count()
的PHP手册:
返回array_or_countable中的元素数。 当 参数既不是数组也不是具有已实现Countable的对象 接口,将返回1。如果有一个例外 array_or_countable为NULL,将返回0。
从PHP 7.2开始,尝试在不可数的内容上使用count()
会产生警告,例如
参数必须是实现Countable
的数组或对象