php—ArrayAccess接口

伊谢尔伦
Freigeben: 2016-11-22 11:01:27
Original
1428 Leute haben es durchsucht

提供像访问数组一样访问对象的能力的接口。

接口摘要

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 )
}
Nach dem Login kopieren

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[] = &#39;Append 1&#39;;
    $obj[] = &#39;Append 2&#39;;
    $obj[] = &#39;Append 3&#39;;
    print_r($obj);
?>
Nach dem Login kopieren

以上例程的输出类似于:

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
        )
)
Nach dem Login kopieren

方法列表

ArrayAccess::offsetExists — 检查一个偏移位置是否存在

ArrayAccess::offsetGet — 获取一个偏移位置的值

ArrayAccess::offsetSet — 设置一个偏移位置的值

ArrayAccess::offsetUnset — 复位一个偏移位置的值


Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!