Countable
Nugget posted by Mark Fenoglio
September 27, 2009

One important part of my frameworks is foundation classes designed to manage collections of data: they all inherit from IWIterator and adhere to the SPL-defined Iterator interface.

In many places in my code, I accept both IWIterators and basic PHP arrays. Whenever possible, I want to treat them in like fashion. One tool for doing this is the SPL-defined Countable interface.

Partial Listing: /fw/foundation/IWIterator.php
<?php

abstract class IWIterator implements Iterator, Countable
{
    protected $array;
    
    // only method required for the Countable interface
    function count()
    {
        return count($this->array);
    }
    ...
}

?>

Now I can use the count() function on both a PHP array and an IWArray instance. For the example below, I could write count($php_array) and count($iw_array) and both will work as expected.

Code Snippet: /ad_hoc/countable.php
<?php

$php_array = array();
$iw_array = new IWArray;

?>