Rumah > Artikel > pembangunan bahagian belakang > Antara muka PHP ArrayAccess
Dalam PHP, kelas ArrayAccess#🎜 digunakan untuk membangunkan antara muka# Kelas menyediakan akses seperti tatasusunan kepada salah satu sifat tatasusunan. Sifat tatasusunan sedemikian boleh dimanipulasi semasa penciptaan objek tanpa mendedahkannya. ArrayAccessAntaramuka mentakrifkan kaedah abstrak berikut
SyntaxArrayAccess { /* 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 }
Syntax<?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);
?>
Kaedah
#🎜🎜 offsetExists - Sama ada ofset wujud
ArrayAccess::offsetGet - Offset untuk mendapatkan semula #🎜🎜🎜##🎜🎜🎜🎜🎜 offsetSet
- Berikan nilai kepada offset yang ditentukanArrayAccess::offsetUnset
- Nyahset offset.ArrayAccess::offsetUnset
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 ) )Output
<?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); ?>
Atas ialah kandungan terperinci Antara muka PHP ArrayAccess. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!