這段程式碼是一個範例。透過使用像這樣的類別,您有機會建立繼承其他類別的類別,但同時擁有繼承 ArrayObject 的類別的大部分功能(類似多重繼承)。
<?php
class foo
{
public $foo = 'foo';
} class foobar extends foo implements ArrayAccess,IteratorAggregate,Countable
{
public function offsetExists($offset)
{
$array = array(1, 2, 3, 4);
return array_key_exists($offset, $array);
}
public function offsetGet($offset)
{
$array = array(1, 2, 3, 4);
return $array[$offset];
}
public function offsetSet($offset, $value)
{
}
public function offsetUnset($offset)
{
}
function count()
{
$array = array(1, 2, 3, 4);
return count($array);
} function getArray()
{
return array(1, 2, 3, 4);
} function getIterator()
{
return new ArrayIterator(array(1, 2, 3, 4));
} function __toString()
{
return 'String test';
} } $foobar = new foobar();
print $foobar[0].'<br/>';
print $foobar->foo.'<br/>';
print count($foobar).'<br/>';
foreach ($foobar as $k=>$v)
{
print $k.'=>'.$v.'<br/>';
} var_dump($foobar->getArray());
print $foobar;
?>
要正確使用,除了 getArray() 之外,您必須定義所有這些方法。
瀏覽 SPL 的原始碼會很有幫助。
ps.: 抱歉我的英文不好