Example #1
0
    public function offsetGet($key)
    {
        if (array_key_exists($key, get_object_vars($this))) {
            return $this->{$key};
        }
    }
    public function offsetUnset($value)
    {
        if (array_key_exists($value, get_object_vars($this))) {
            unset($this->{$value});
        }
    }
    public function offsetExists($offset)
    {
        return array_key_exists($offset, get_object_vars($this));
    }
    public function getIterator()
    {
        return new ArrayIterator($this);
    }
}
$A = new Article('SPL Rocks', 'Joe Bloggs', 'PHP');
// Loop (getIterator will be called automatically)
echo 'Looping with foreach:<div>';
foreach ($A as $field => $value) {
    echo "{$field} : {$value}<br>";
}
echo '</div>';
// Get the size of the iterator (see how many properties are left)
echo "Object has " . sizeof($A->getIterator()) . " elements";
Example #2
0
    }
    /**
     * Defined by ArrayAccess interface
     * Check value exists, given it's key e.g. isset($A['title'])
     * @param mixed key (string or integer)
     * @return boolean
     */
    function offsetExists($offset)
    {
        return array_key_exists($offset, get_object_vars($this));
    }
    /**
     * Defined by IteratorAggregate interface
     * Returns an iterator for for this object, for use with foreach
     * @return ArrayIterator
     */
    function getIterator()
    {
        return new ArrayIterator($this);
    }
}
$A = new Article('SPL Rocks', 'Joe Bloggs', 'PHP');
// Loop (getIterator will be called automatically)
echo 'Looping with foreach:<pre>';
foreach ($A as $field => $value) {
    echo "{$field} : {$value}<br>";
}
echo '</pre>';
// Get the size of the iterator (see how many properties are left)
echo "Object has " . count($A->getIterator()) . " elements";