PHPでConstな配列を作る

こんな定数はイヤなので定数な配列を作れないものか。

define("MONTH_1", "Jan");
define("MONTH_2", "Feb");

というわけで作ってみた

ArrayAccessインタフェースを使います。

<?php
class ConstArray implements ArrayAccess {
  public function __construct(array $values) {
    $this->values = $values;
  }

  // 参照(許可。存在しない場合は例外投げる)
  public function offsetGet($offset) {
    if(!$this->offsetExists($offset)) {
      throw new Exception('値がないです');
    }
    return $this->values[$offset];
  }

  // 更新、追加(禁止)
  public function offsetSet($offset, $value) {
    throw new Exception('追加、上書き禁止');
  }

  // 存在確認(許可)
  public function offsetExists($offset) {
    return isset($this->values[$offset]);
  }

  // 削除(禁止)
  public function offsetUnset($offset) {
    throw new Exception('アンセット禁止');
  }
}

// 使用例
$MONTH = new ConstArray(array(1=>"Jan", 2=>"Feb"));

?>

動作確認

参照
$ php -r 'require("const.php"); echo "1月は$MONTH[1]\n";'
1月はJan
$ php -r 'require("const.php"); echo "3月は$MONTH[3]\n";'
Fatal error: Uncaught exception 'Exception' with message '値がないです'
更新、追加
$ php -r 'require("const.php"); $MONTH[1] = "May";'
Fatal error: Uncaught exception 'Exception' with message '追加、上書き禁止'
$ php -r 'require("const.php"); $MONTH[5] = "May";'
Fatal error: Uncaught exception 'Exception' with message '追加、上書き禁止'
存在確認
$ php -r 'require("const.php"); echo isset($MONTH[1])?"Exist":"Not Exist";'
Exist
$ php -r 'require("const.php"); echo isset($MONTH[3])?"Exist":"Not Exist";'
Not Exist
削除
$ php -r 'require("const.php"); unset($MONTH[3]);'
Fatal error: Uncaught exception 'Exception' with message 'アンセット禁止'

まぁ正直あんまり気にせず普通の配列使ってますがw