php—ArrayAccess interface

伊谢尔伦
Release: 2016-11-22 11:01:27
Original
1479 people have browsed it

An interface that provides the ability to access objects like arrays.

Interface summary

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 )
}
Copy after login

Example #1 Usage example

<?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);
?>
Copy after login

The output of the above routine is similar to:

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
        )
)
Copy after login

Method list

ArrayAccess::offsetExists — Check whether an offset position exists

ArrayAccess::offsetGet — Get The value of an offset position

ArrayAccess::offsetSet — Set the value of an offset position

ArrayAccess::offsetUnset — Reset the value of an offset position


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!