在PHP中,使用ArrayAccess接口来开发一个类,该类提供对数组的访问,就像对其中一个属性(数组)的访问一样。这样的数组属性可以在对象创建期间不暴露的情况下进行操作。ArrayAccess接口定义以下抽象方法
ArrayAccess { /* Methods */ abstract public offsetExists ( mixed $offset ) : bool abstract public offsetGet ( mixed $offset ) : mixed abstract public offsetSet ( mixed $offset , mixed $value ) : void abstract public offsetUnset ( mixed $offset ) : void }
ArrayAccess::offsetExists- 偏移量是否存在
ArrayAccess::offsetGet-要获取的偏移量
ArrayAccess::offsetSet-将值分配给指定的偏移量
ArrayAccess::offsetUnset-取消偏移量。
在下面的示例中,关联数组是myclass的内部私有属性。键用作偏移量。我们可以设置,释放和取消设置数组中的项目。如果未给出offset,则将其视为整数,每次递增到下一个索引。
<?php class myclass implements ArrayAccess { private $arr = array(); public function __construct() { $this->arr = array( "Mumbai" => "Maharashtra", "Hyderabad" => "A.P.", "Patna" => "Bihar", ); } public function offsetSet($offset, $value) { if (is_null($offset)) { $this->arr[] = $value; } else { $this->arr[$offset] = $value; } } public function offsetExists($offset) { return isset($this->arr[$offset]); } public function offsetUnset($offset) { unset($this->arr[$offset]); } public function offsetGet($offset) { return isset($this->arr[$offset]) ? $this->arr[$offset] : null; } } $obj = new myclass(); var_dump(isset($obj["Mumbai"])); var_dump($obj["Mumbai"]); unset($obj["Mumbai"]); var_dump(isset($obj["Mumbai"])); $obj["Bombay"] = "Maharashtra"; var_dump($obj["Bombay"]); $obj["Chennai"] = 'Tamilnadu'; $obj[] = 'New State'; $obj["Hyderabad"] = 'Telangana'; print_r($obj); ?>
输出结果
上面的程序显示以下输出
bool(true) string(11) "Maharashtra" bool(false) string(11) "Maharashtra" myclass Object( [arr:myclass:private] => Array( [Hyderabad] => Telangana [Patna] => Bihar [Bombay] => Maharashtra [Chennai] => Tamilnadu [0] => New State ) )
类的array属性也可以是索引数组。在这种情况下,元素的索引(从0开始)充当偏移量。当调用offsetSet(0没有偏移参数的方法时,数组的索引递增到下一个可用整数
<?php class myclass implements ArrayAccess { private $arr = array(); public function __construct() { $this->arr = array("Mumbai", "Hyderabad", "Patna"); } public function offsetSet($offset, $value) { if (is_null($offset)) { $this->arr[] = $value; } else { $this->arr[$offset] = $value; } } public function offsetExists($offset) { eturn isset($this->arr[$offset]); } public function offsetUnset($offset) { unset($this->arr[$offset]); } public function offsetGet($offset) { return isset($this->arr[$offset]) ? $this->arr[$offset] : null; } } $obj = new myclass(); var_dump(isset($obj[0])); var_dump($obj[0]); unset($obj[0]); var_dump(isset($obj[0])); $obj[3] = "Pune"; var_dump($obj[3]); $obj[4] = 'Chennai'; $obj[] = 'NewDelhi'; $obj[2] = 'Benguluru'; print_r($obj); ?>
输出结果
上面的程序显示以下输出
bool(true) string(6) "Mumbai" bool(false) string(4) "Pune" myclass Object( [arr:myclass:private] => Array( [1] => Hyderabad [2] => Benguluru [3] => Pune [4] => Chennai [5] => NewDelhi ) )