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().
interface Countable
{
function count();
}
Usage Example
The example given is the not the normal practice and shouldn’t be used in real world applications.
class CountableObject implements Countable
{
private $count;
function __construct($count = 10)
{
$this->count = (int) $count;
}
function count()
{
return $this->count;
}
}
If the user is using PHP 5.0, then they can still get the amount of elements.
$countable = new CountableObject(20); echo $countable->count();
If the user has PHP 5.1 or above, then they can use the magic the interface provides.
$countable = new CountableObject(20); count($countable);
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.
Possibly Related Posts:
- Paying Off Debt Revisited
- Thou Art God
- Saying Good Bye to Dollhouse
- Where the Wild Things Are Movie Review
- Why Choose 1st Financial Bank?
Tags: Countable, Interface, PHP, Standard PHP Library