简体   繁体   English

带问题的 ArrayAccess 演练

[英]ArrayAccess Walkthrough with Questions

I have some questions about the implementation of implementing ArrayAccess in PHP.我对在ArrayAccess中实现 ArrayAccess 的实现有一些疑问。

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:问题:

  1. 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?我不是在问为什么我们必须实现ArrayAccess ,因为我假设它是 PHP 引擎自动识别并调用实现的继承函数的特殊接口?
  2. Why are we declaring the implemented function public?为什么我们将实现的 function 公开? 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.它们不应该是私有的,因为在调用$obj["two"]时不会从外部调用函数。
  3. Is there a special reason to assign the filled-array in __constructor function?__constructor function 中分配填充数组是否有特殊原因? This is the constructor function I know but in this case what kind of help it is being of.这是构造函数 function 我知道但在这种情况下它有什么样的帮助。
  4. What's the difference between ArrayAccess and ArrayObject ? ArrayAccess 和ArrayAccess有什么ArrayObject I am thinking the class I implemented by inheriting the ArrayAccess doesn't support iteration?我在想我通过继承 ArrayAccess 实现的ArrayAccess不支持迭代?
  5. How could we implement object-indexing without implementing ArrayAccess ?我们如何在不实现ArrayAccess的情况下实现对象索引?

Thanks...谢谢...

  1. Correct正确的
  2. Because the interface defines them as public, therefore you have to also因为接口将它们定义为公共的,所以你也必须
  3. You don't have to write the constructor that way if you don't want to*如果您不想这样做,则不必那样编写构造函数*
  4. ArrayAccess is an interface , ArrayObject is a class (which itself implements ArrayAccess ) ArrayAccess是一个interfaceArrayObject是一个 class (它本身实现ArrayAccess
  5. No other way that I'm aware of没有其他我知道的方式

* Your constructor could look like this * 你的构造函数可能看起来像这样

public function __construct( array $data ) {
    $this->container = $data;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM