在 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 - 要检索的偏移量< /p>
ArrayAccess::offsetSet - 为指定的偏移量分配一个值
ArrayAccess::offsetUnset - 取消设置偏移量。
ArrayAccess::offsetUnset - 取消设置偏移量。 p>
在下面的示例中,关联数组是 myclass 的内部私有属性。键充当偏移量。我们可以设置、检索和取消设置数组中的项目。如果未给出偏移量,则会将其视为整数,每次递增到下一个索引。
实时演示
<?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 ) )
类的数组属性也可以是索引数组。在这种情况下,元素的索引(从 0 开始)充当偏移量。当调用不带 offset 参数的 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 ) )
以上是PHP ArrayAccess 接口的详细内容。更多信息请关注PHP中文网其他相关文章!