在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 - 取消設定偏移量。
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中文網其他相關文章!