ArrayAccess(陣列式訪問)介面
(PHP 5, PHP 7, PHP 8)
簡介
提供像訪問陣列一樣訪問對象的能力的介面。
介面摘要
interface ArrayAccess {
/* 方法 */
}示例 #1 Basic usage
<?php
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;
}
}
$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 ) )
目錄
- ArrayAccess::offsetExists — 檢查一個偏移位置是否存在
- ArrayAccess::offsetGet — 獲取一個偏移位置的值
- ArrayAccess::offsetSet — 設定一個偏移位置的值
- ArrayAccess::offsetUnset — 復位一個偏移位置的值