我现在正在做一个项目,我有一个实现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]);
}
}发布于 2010-06-14 12:18:32
在我看来,就像文件顶部的namespace或use指令,让它看起来与错误的ArrayAccess接口兼容。但是如果没有这些指令就无法确定。
一般情况下:
您自己的命名空间不应该以反斜杠开头或结尾:
用途:namespace Web\Http;
不要使用这样的词:namespace \Web\Http;或namespace \Web\Http\;
对于文件中引用的每个类和接口,添加一个use指令:
namespace MyProject;
use MyLibrary\BaseClass; // note no backslash before the namespace name
use \ArrayAccess;
use \Iterator;
use \Countable;
class MyClass extends BaseClass implements ArrayAccess, Iterator, Countable
{
/* Your implementation goes here as normal */
}发布于 2010-02-13 13:49:02
唯一吸引我眼球的是:
public function offsetGet($offset) {
return isset ($this->params[$offset]) ? $this->params[$offset] : NULL;
}也许用以下文字取代它:
public function offsetGet($offset) {
return (isset ($this->params[$offset]) ? $this->params[$offset] : NULL);
}就能完成这个把戏。
它也可能是一个语法错误,拖着你没有粘贴的代码的那一部分。
https://stackoverflow.com/questions/2257664
复制相似问题