Count elements for objects implementing ArrayAccess using count()?

前端 未结 1 765
無奈伤痛
無奈伤痛 2021-01-18 09:15

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 d

相关标签:
1条回答
  • 2021-01-18 09:54

    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 讨论(0)
提交回复
热议问题