PHpullh
학습 라이브러리/PHP/ArrayAccess 구현

PHP · 객체지향

ArrayAccess 구현

객체를 배열처럼 다루고 싶을 때 ArrayAccess를 구현하는 예제입니다.

객체지향고급ArrayAccessobjectarray-like

핵심 설명

객체를 배열처럼 다루고 싶을 때 ArrayAccess를 구현하는 예제입니다.

PHP code

<?php
class Bag implements ArrayAccess {
    private array $items = [];

    public function offsetExists(mixed $offset): bool { return isset($this->items[$offset]); }
    public function offsetGet(mixed $offset): mixed { return $this->items[$offset] ?? null; }
    public function offsetSet(mixed $offset, mixed $value): void { $this->items[$offset] = $value; }
    public function offsetUnset(mixed $offset): void { unset($this->items[$offset]); }
}

$bag = new Bag();
$bag['lang'] = 'php';
echo $bag['lang'];

학습 팁

클래스 예제는 생성자, 가시성, 협력 객체의 책임을 함께 보면 실무 감각이 빨리 붙습니다.

주의할 점

가시성, final, readonly 제약을 무시하면 객체 설계가 금방 흐트러집니다.

자주 묻는 질문

ArrayAccess 구현란 무엇인가요?

객체를 배열처럼 다루고 싶을 때 ArrayAccess를 구현하는 예제입니다.

ArrayAccess 구현 학습 시 주의할 점은 무엇인가요?

가시성, final, readonly 제약을 무시하면 객체 설계가 금방 흐트러집니다.