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
ArrayAccesssince 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
__constructorfunction? This is the constructor function I know but in this case what kind of help it is being of. - What’s the difference between
ArrayAccessandArrayObject? I am thinking the class I implemented by inheriting theArrayAccessdoesn’t support iteration? - How could we implement object-indexing without implementing
ArrayAccess?
Thanks…
ArrayAccessis an interface,ArrayObjectis a class (which itself implementsArrayAccess)* Your constructor could look like this