基本的な配列を使用する必要がある場合は、作成時にキーを入力するだけです。
$cartoons = array(
'Tom and Jerry' => new Cartoon('Tom and Jerry'),
'Cheburashka' => new Cartoon('Cheburashka'),
);
または、さまざまな配列/反復関連のインターフェイスを実装し、通常の配列として使用できるコンテナー オブジェクトを作成できます。
class CartoonArray extends ArrayObject {
public function __construct($input, $flags = 0, $iterator_class = "ArrayIterator") {
parent::__construct(array(), $flags, $iterator_class);
// since the original ArrayObject implemented in C and they don't it won't pick up our overriden ossetSet we have to type it out here explicitly
foreach ($input as $value) {
$this->offsetSet(null, $value);
}
}
public function offsetSet($index, $value) {
parent::offsetSet($value->title, $value);
}
}
$cartoons = new CartoonArray(array(new Cartoon('Tom and Jerry'), new Cartoon('Cheburashka')));
$cartoons[] = new Cartoon('Sesame street');
print $cartoons['Tom and Jerry']->title;
unset($cartoons['Tom and Jerry']);
foreach ($cartoons as $k => $v) {
print $k."\n";
}