[英]PHP 5.3 and interface \ArrayAccess
我现在正在一个项目上,并且有一个实现ArrayAccess接口的类。
Howewer,出现一个错误,提示我的实现:
必须与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]);
}
}
在我看来,您的namespace
或文件顶部的use
指令使它查找与之兼容的错误ArrayAccess
接口。 虽然没有这些指令也无法确定。
一般来说:
您自己的名称空间不应以反斜杠开头或结尾:
使用: namespace Web\\Http;
不要 使用类似以下内容的 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 */
}
在这里唯一引起我注意的是:
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);
}
会完成技巧。
这也可能是语法错误,它会从您尚未粘贴的部分代码中拖延下来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.