当一个类实现了ArrayAccess
接口(interface)时,它就可以作为数组发挥作用,完成 OffsetGet、OffsetSet 等。
我没有看到的一件事是当我们想要 count()
或 sizeof()
时的实现,以我对 PHP 的有限了解,数量相同。
是否有类似的东西已经在标准 PHP 中实现了?
最佳答案
正确的方法是执行 Countable interface
Example #1 Countable::count() example
<?php
class myCounter implements Countable {
public function count() {
static $count = 0;
return ++$count;
}
}
$counter = new myCounter;
for($i=0; $i<10; ++$i) {
echo "I have been count()ed " . count($counter) . " times\n";
}
换句话说,您自己实现 count()
应该返回的逻辑。
关于php - 使用 count() 计算实现 ArrayAccess 的对象的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5289705/