开发者

Count elements for objects implementing ArrayAccess using count()?

开发者 https://www.devze.com 2023-02-16 18:09 出处:网络
When a class implements the ArrayAccess interface, it becomes ready to function as an array, complete with OffsetGet, OffsetSet and so on.

When a class implements the ArrayAccess interface, it becomes ready to function as an array, complete with OffsetGet, OffsetSet and so on.

One thing I didn't see was an implementation for when we want to count() or sizeof() it, which, in m开发者_运维知识库y limited knowledge of PHP, amounts to the same.

Is there anything like it already implemented in standard PHP?


The correct way would be to implement the 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";
}

In other words, you implement the logic what count() should return yourself.

0

精彩评论

暂无评论...
验证码 换一张
取 消