> 백엔드 개발 > PHP 튜토리얼 > php - ArrayAccess 인터페이스

php - ArrayAccess 인터페이스

伊谢尔伦
풀어 주다: 2016-11-22 11:01:27
원래의
1603명이 탐색했습니다.

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

인터페이스 요약

1

2

3

4

5

6

7

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 사용 예

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

<?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);

?>

로그인 후 복사

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿