LoginSignup
14
15

More than 5 years have passed since last update.

PHPで固定型のコレクションクラスを作る

Posted at

PHPの通常の配列は何でも投入できる。
同じ型の要素だけが含まれる配列であると保証したい場合、setterで制限を掛けるとよい。

ArrayObjectをextendsするのが楽。

<?php
// intだけに制限する
class IntArray extends ArrayObject
{
  function offsetSet($offset, $value) {
    if (is_int($value)) {
      return parent::offsetSet($offset, $value);
    }
    throw new InvalidArgumentException;
  }
}

// Hogeクラスのインスタンスだけに制限する
class HogeArray extends ArrayObject
{
  function offsetSet($offset, $value) {
    if ($value instanceof Hoge) {
      return parent::offsetSet($offset, $value);
    }
    throw new InvalidArgumentException;
  }
}

ちょっとかっちりしたクラスになる。

14
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
15