带有问题的 ArrayAccess 演练
我对在 PHP 中实现 ArrayAccess 的实现有一些疑问。
下面是示例代码:
class obj implements arrayaccess {
private $container = array();
public function __construct() {
$this->container = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
}
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;
}
}
问题:
- 我不是问为什么我们必须实现
ArrayAccess
,因为我假设它是 PHP 引擎识别并调用已实现的继承的特殊接口。自动功能? - 为什么我们要公开实现的功能?因为我假设它们是自动调用的特殊函数。它们不应该是私有的,因为在调用
$obj["two"]
时,函数不会从外部调用。 - 在 __constructor 函数中分配填充数组是否有特殊原因?这是我知道的构造函数,但在这种情况下它有什么样的帮助。
ArrayAccess
和ArrayObject
之间有什么区别?我在想我通过继承 ArrayAccess 实现的类不支持迭代?- 我们如何在不实现 ArrayAccess 的情况下实现对象索引?
谢谢...
I have some questions about the implementation of implementing ArrayAccess
in PHP.
Here is the sample code:
class obj implements arrayaccess {
private $container = array();
public function __construct() {
$this->container = array(
"one" => 1,
"two" => 2,
"three" => 3,
);
}
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;
}
}
Questions:
- I am not asking why we do have to implement
ArrayAccess
since I am assuming it is special interface that PHP Engine recognizes and calls the implemented inherited functions automatically? - Why are we declaring the implemented function public? Since I assume they are special functions called automatically. Shouldn't they be private since when calling saying
$obj["two"]
the functions are not be called from outside. - Is there a special reason to assign the filled-array in
__constructor
function? This is the constructor function I know but in this case what kind of help it is being of. - What's the difference between
ArrayAccess
andArrayObject
? I am thinking the class I implemented by inheriting theArrayAccess
doesn't support iteration? - How could we implement object-indexing without implementing
ArrayAccess
?
Thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ArrayAccess
是一个 接口,ArrayObject
是一个类(它本身实现ArrayAccess
)* 您的构造函数可能如下所示
ArrayAccess
is an interface,ArrayObject
is a class (which itself implementsArrayAccess
)* Your constructor could look like this