array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'zh', ), 'this' => array ( 0 => 'class.arrayaccess.php', 1 => 'ArrayAccess', ), 'up' => array ( 0 => 'reserved.interfaces.php', 1 => '预定义接口和类', ), 'prev' => array ( 0 => 'throwable.tostring.php', 1 => 'Throwable::__toString', ), 'next' => array ( 0 => 'arrayaccess.offsetexists.php', 1 => 'ArrayAccess::offsetExists', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'zh', 'path' => 'language/predefined/arrayaccess.xml', ), 'extra_header_links' => array ( 'rel' => 'alternate', 'href' => '/manual/en/feeds/class.arrayaccess.atom', 'type' => 'application/atom+xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 5, PHP 7, PHP 8)
提供像访问数组一样访问对象的能力的接口。
示例 #1 基础用法
<?php
class Obj implements ArrayAccess {
public $container = [
"one" => 1,
"two" => 2,
"three" => 3,
];
public function offsetSet($offset, $value): void {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
}
public function offsetExists($offset): bool {
return isset($this->container[$offset]);
}
public function offsetUnset($offset): void {
unset($this->container[$offset]);
}
public function offsetGet($offset): mixed {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
}
$obj = new Obj;
var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);
?>
以上示例的输出类似于:
bool(true) int(2) bool(false) string(7) "A value" obj Object ( [container:obj:private] => Array ( [one] => 1 [three] => 3 [two] => A value [0] => Append 1 [1] => Append 2 [2] => Append 3 ) )