如果您必须使用基本数组,您可以在创建它们时简单地键入键:
$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";
}