6

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 my limited knowledge of PHP, amounts to the same.

Is there anything like it already implemented in standard PHP?

Leigh
  • 12,859
  • 3
  • 39
  • 60
Felipe
  • 11,557
  • 7
  • 56
  • 103

1 Answers1

13

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.

Lukas
  • 1,479
  • 8
  • 20
Gordon
  • 312,688
  • 75
  • 539
  • 559
  • Hmm.. I see... But this would require me to write `$myInstance->count()` rather than `count($myInstance)`? I know it's silly but I was really looking for a way to make it return custom behaviour upon being passed as parameter to the native `count($param)` function on PHP. – Felipe Mar 13 '11 at 13:47
  • @Felipe It does that. Please look at the Manual. It's doing exactly what you are asking. Updated code. – Gordon Mar 13 '11 at 13:51