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:
- 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...
- Correct
- Because the interface defines them as public, therefore you have to also
- You don't have to write the constructor that way if you don't want to*
ArrayAccess
is an interface,ArrayObject
is a class (which itself implementsArrayAccess
)- No other way that I'm aware of
* Your constructor could look like this
public function __construct( array $data ) {
$this->container = $data;
}
精彩评论