>  기사  >  백엔드 개발  >  php - ArrayAccess 인터페이스

php - ArrayAccess 인터페이스

伊谢尔伦
伊谢尔伦원래의
2016-11-22 11:01:271423검색

배열과 같은 객체에 액세스하는 기능을 제공하는 인터페이스입니다.

인터페이스 요약

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 )
}

예제 #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);
?>

위 루틴의 출력은 다음과 유사합니다.

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 — 설정 offset 오프셋 위치 값

ArrayAccess::offsetUnset — 오프셋 위치 값을 재설정합니다


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.