你的类实现了ArrayAccess
接口。这意味着它实现了以下方法:
ArrayAccess {
abstract public boolean offsetExists ( mixed $offset )
abstract public mixed offsetGet ( mixed $offset )
abstract public void offsetSet ( mixed $offset , mixed $value )
abstract public void offsetUnset ( mixed $offset )
}
这允许您对此类的实例使用数组访问$var[$offset]
。这是一个像这样的类的标准实现,使用$container
数组来保存属性:
class Strategie implements ArrayAccess {
private $container = array();
public function __construct() {
$this->container = array(
"something" => 1,
);
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
如果不查看它的实际实现Strategie
或派生它的类,很难判断它实际在做什么。
但是使用它,您可以控制类的行为,例如,在访问不存在的偏移量时。假设我们替换offsetGet($offset)
为:
public function offsetGet($offset) {
if (isset($this->container[$offset])) {
return $this->container[$offset];
} else {
Logger.log('Tried to access: ' + $offset);
return $this->default;
}
}
现在,每当我们尝试访问一个不存在的偏移量时,它将返回一个默认值(例如:)$this->default
并记录一个错误,例如。
请注意,您可以使用魔术方法__set()
、__get()
和来完成类似__isset()
的行为__unset()
。我刚刚列出的魔术方法之间的区别在于ArrayAccess
您将通过$obj->property
而不是访问属性$obj[offset]