SPL Countable

Introduction

Allows the object to be used in the PHP count() function. Even on PHP 5.0, it can still be used, if called as a class method.

Its purpose is best served in iterators or classes who elements are dynamic.

Interface

It only has one method that needs to be implemented, which is count().

[php] interface Countable { function count(); } [/php]

Usage Example

The example given is the not the normal practice and shouldn't be used in real world applications.

[php] class CountableObject implements Countable { private $count;

function __construct($count = 10) { $this->count = (int) $count; }

function count() { return $this->count; } } [/php]

If the user is using PHP 5.0, then they can still get the amount of elements.

[php] $countable = new CountableObject(20); echo $countable->count(); [/php]

If the user has PHP 5.1 or above, then they can use the magic the interface provides.

[php] $countable = new CountableObject(20); count($countable); [/php]

Iterator Example

This is how you really should use the countable interface in real world applications.

References

Official Countable Documentation - From offical SPL documentation site.