开发者

ArrayAccess Walkthrough with Questions

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 开发者_Go百科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?
  2. 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.
  3. 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.
  4. What's the difference between ArrayAccess and ArrayObject? I am thinking the class I implemented by inheriting the ArrayAccess doesn't support iteration?
  5. How could we implement object-indexing without implementing 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)
  5. No other way that I'm aware of

* Your constructor could look like this

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜