ArrayObject
SPL means Standard PHP Library ArrayObject allows arrays to work as objects
$array= array('a','b','c');
$obj = new ArrayObject($array);
$obj->append('d');
echo $obj->count(); // 4
$iterator = $obj->getIterator();
while($iterator->valid()) {
echo $iterator->current(); // abcd
$iterator->next();
}
Serializable
Interface for customized serializing
class Obj implements Serializable
{
private $data;
public function __construct()
{
$this->data = "My private data";
}
public function serialize()
{
return serialize($this->data);
}
public function unserialize($str)
{
return unserialize($str);
}
}
$obj = new Obj();
echo $str = $obj->serialize(); // s:15:"My private data";
echo $obj->unserialize($str); // My private data
ArrayAccess
Interface to provide accessing objects as arrays
class myArray implements ArrayAccess
{
protected $array = array();
public function offsetExists($offset)
{
return array_key_exists($this->array[$offset]);
}
public function offsetGet($offset)
{
return $this->array[$offset];
}
public function offsetSet($offset, $value)
{
if (! is_numeric($offset)) {
throw new Exception ("Invalid Offset!");
}
$this->array[$offset] = $value;
}
public function offsetUnset($offset)
{
unset($this->array[$offset]);
}
}
$ma = new myArray();
$ma[1] = 2; // Works
$ma['a'] = 3; // Throws exception
Iterator
Interface for external objects that can be iterated themselves
class myArray implements Iterator
{
private $_data = array('foo', 'bar', 'baz');
private $_current = 0;
public function current()
{
return $this->_data[$this->_current];
}
public function next()
{
$this->_current += 1;
}
public function key()
{
return $this->_current;
}
public function valid()
{
return isset($this->_data[$this->_current]);
}
public function rewind()
{
$this->_current = 0;
}
}
$ma = new myArray();
echo $ma->valid(); // 1
echo $ma->current(); // foo
$ma->next();
$ma->next();
echo $ma->key(); // 2
$ma->rewind();
while($ma->valid()) {
echo $ma->current(); // foobarbaz
$ma->next();
}
Last update: 496 days ago