【发布时间】:2010-02-13 13:25:04
【问题描述】:
我现在正在做一个项目,我有一个实现 ArrayAccess 接口的类。
但是,我收到一个错误,说明我的实现:
必须与 ArrayAccess::offsetSet() 兼容。
我的实现如下所示:
public function offsetSet($offset, $value) {
if (!is_string($offset)) {
throw new \LogicException("...");
}
$this->params[$offset] = $value;
}
所以,在我看来,我的实现是正确的。知道有什么问题吗?非常感谢!
类如下所示:
class HttpRequest implements \ArrayAccess {
// tons of private variables, methods for working
// with current http request etc. Really nothing that
// could interfere with that interface.
// ArrayAccess implementation
public function offsetExists($offset) {
return isset ($this->params[$offset]);
}
public function offsetGet($offset) {
return isset ($this->params[$offset]) ? $this->params[$offset] : NULL;
}
public function offsetSet($offset, $value) {
if (!is_string($offset)) {
throw new \LogicException("You can only assing to params using specified key.");
}
$this->params[$offset] = $value;
}
public function offsetUnset($offset) {
unset ($this->params[$offset]);
}
}
类如下所示:
class HttpRequest implements \ArrayAccess {
// tons of private variables, methods for working
// with current http request etc. Really nothing that
// could interfere with that interface.
// ArrayAccess implementation
public function offsetExists($offset) {
return isset ($this->params[$offset]);
}
public function offsetGet($offset) {
return isset ($this->params[$offset]) ? $this->params[$offset] : NULL;
}
public function offsetSet($offset, $value) {
if (!is_string($offset)) {
throw new \LogicException("You can only assing to params using specified key.");
}
$this->params[$offset] = $value;
}
public function offsetUnset($offset) {
unset ($this->params[$offset]);
}
}
【问题讨论】:
-
哪一行报错了?
-
类声明行(X类实现\ArrayAccess)。
-
如果您提供课程的其余部分(或课程的缩短版),可能会有所帮助。
-
如果你停止它抛出异常会发生什么?
-
你的类声明在命名空间内吗?例如你在文件顶部有
namespace My\Namespace;声明吗?如果没有,您不需要限定 ArrayAccess。您也可以尝试“使用”ArrayAccess而不是完全限定它。这似乎是一个奇怪的错误,所以我只是把东西扔在那里......