ArrayAccess interface

(PHP 5, PHP 7, PHP 8)


소개

액세스 개체를 배열로 제공하기 위한 인터페이스입니다.


인터페이스 개요

                  
interface ArrayAccess {
  /* Methods */
  public offsetExists(mixed $offset): bool
  public offsetGet(mixed $offset): mixed
  public offsetSet(mixed $offset, mixed $value): void
  public offsetUnset(mixed $offset): void
}
                  
                

Examples

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

)
                

목차