Computer >> 컴퓨터 >  >> 프로그래밍 >> PHP

PHP ArrayAccess 인터페이스 완벽 가이드: 객체를 배열처럼 다루는 방법

PHP ArrayAccess 인터페이스란?

PHP에서 ArrayAccess 인터페이스는 클래스 내부의 배열 프로퍼티를 마치 일반 배열처럼 접근하고 조작할 수 있도록 해주는 기능을 제공합니다. 이 인터페이스를 구현하면 객체 생성 시 배열 프로퍼티를 외부에 직접 노출하지 않으면서도 $obj["키"]와 같은 배열 문법으로 값에 접근할 수 있습니다.

ArrayAccess 인터페이스는 다음과 같은 추상 메서드들을 정의하고 있습니다.

문법(Syntax)

ArrayAccess {
   /* 메서드 */
   abstract public offsetExists ( mixed $offset ) : bool
   abstract public offsetGet ( mixed $offset ) : mixed
   abstract public offsetSet ( mixed $offset , mixed $value ) : void
   abstract public offsetUnset ( mixed $offset ) : void
}

주요 메서드

  • ArrayAccess::offsetExists − 지정한 오프셋(offset)이 존재하는지 여부를 확인합니다.
  • ArrayAccess::offsetGet − 지정한 오프셋에 해당하는 값을 가져옵니다.
  • ArrayAccess::offsetSet − 지정한 오프셋에 값을 할당합니다.
  • ArrayAccess::offsetUnset − 지정한 오프셋을 제거(unset)합니다.

예제 1: 연관 배열(Associative Array) 활용

다음 예제에서는 연관 배열이 myclass의 private 프로퍼티로 선언되어 있습니다. 배열의 키(key)가 오프셋 역할을 하며, 이를 통해 배열 항목을 설정(set)·조회(get)·제거(unset)할 수 있습니다. 오프셋 없이 값만 전달하면 해당 값은 자동으로 다음 정수 인덱스에 추가됩니다.

<?php
class myclass implements ArrayAccess {
   private $arr = array();
   public function __construct() {
      $this->arr = array(
         "Mumbai" => "Maharashtra",
         "Hyderabad" => "A.P.",
         "Patna" => "Bihar",
      );
   }
   public function offsetSet($offset, $value) {
      if (is_null($offset)) {
         $this->arr[] = $value;
      } else {
         $this->arr[$offset] = $value;
      }
   }
   public function offsetExists($offset) {
      return isset($this->arr[$offset]);
   }
   public function offsetUnset($offset) {
      unset($this->arr[$offset]);
   }
   public function offsetGet($offset) {
      return isset($this->arr[$offset]) ? $this->arr[$offset] : null;
   }
}
$obj = new myclass();
var_dump(isset($obj["Mumbai"]));
var_dump($obj["Mumbai"]);
unset($obj["Mumbai"]);
var_dump(isset($obj["Mumbai"]));
$obj["Bombay"] = "Maharashtra";
var_dump($obj["Bombay"]);
$obj["Chennai"] = 'Tamilnadu';
$obj[] = 'New State';
$obj["Hyderabad"] = 'Telangana';
print_r($obj);
?>

실행 결과

위 프로그램을 실행하면 다음과 같은 출력 결과를 확인할 수 있습니다.

bool(true)
string(11) "Maharashtra"
bool(false)
string(11) "Maharashtra"
myclass Object(
   [arr:myclass:private] => Array(
      [Hyderabad] => Telangana
      [Patna] => Bihar
      [Bombay] => Maharashtra
      [Chennai] => Tamilnadu
      [0] => New State
   )

)

참고로 isset()은 값이 null일 때 false를 반환하기 때문에, null 값도 '존재'로 판단해야 하는 경우라면 offsetExists() 내부에서 array_key_exists()를 사용하는 것이 더 안전합니다.

예제 2: 인덱스 배열(Indexed Array) 활용

클래스의 배열 프로퍼티는 인덱스 배열일 수도 있습니다. 이 경우에는 각 요소의 인덱스(0부터 시작)가 오프셋 역할을 하게 됩니다. offsetSet() 메서드를 오프셋 인자 없이 호출하면 배열의 인덱스가 다음으로 사용 가능한 정수로 자동 증가합니다.

<?php
class myclass implements ArrayAccess {
   private $arr = array();
   public function __construct() {
      $this->arr = array("Mumbai", "Hyderabad", "Patna");
   }
   public function offsetSet($offset, $value) {
      if (is_null($offset)) {
         $this->arr[] = $value;
      } else {
         $this->arr[$offset] = $value;
      }
   }
   public function offsetExists($offset) {
      return isset($this->arr[$offset]);
   }
   public function offsetUnset($offset) {
      unset($this->arr[$offset]);
   }
   public function offsetGet($offset) {
      return isset($this->arr[$offset]) ? $this->arr[$offset] : null;
   }
}
$obj = new myclass();
var_dump(isset($obj[0]));
var_dump($obj[0]);
unset($obj[0]);
var_dump(isset($obj[0]));
$obj[3] = "Pune";
var_dump($obj[3]);
$obj[4] = 'Chennai';
$obj[] = 'NewDelhi';
$obj[2] = 'Benguluru';
print_r($obj);
?>

실행 결과

위 프로그램을 실행하면 다음과 같은 출력 결과를 확인할 수 있습니다.

bool(true)
string(6) "Mumbai"
bool(false)
string(4) "Pune"
myclass Object(
   [arr:myclass:private] => Array(
      [1] => Hyderabad
      [2] => Benguluru
      [3] => Pune
      [4] => Chennai
      [5] => NewDelhi
   )

)