php—ArrayAccess介面

來源:互聯網
上載者:User
提供像訪問數組一樣訪問對象的能力的介面。

介面摘要

ArrayAccess {    /* 方法 */    abstract public boolean offsetExists ( mixed $offset )    abstract public mixed offsetGet ( mixed $offset )    abstract public void offsetSet ( mixed $offset , mixed $value )    abstract public void offsetUnset ( mixed $offset )}

Example #1 使用範例

<?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 — 複位一個位移位置的值

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.