LoginSignup
2
0

More than 3 years have passed since last update.

PHPのクラスをforeachで回せるようにする

Last updated at Posted at 2020-02-21

PHPでは普通arrayをforeachしますが、クラスにIteratorAggregate、ArrayAccess、Countableを実装させればforeachで回せるようになります。

配列を直接使うのではなくクラスにすることで、引数に渡せる型を制限したり、クラスにロジックを書けたりして便利です。この考え方をファーストクラスコレクションといいます。

以下は例のコードです。


<?php 

class ListValue implements \IteratorAggregate, \ArrayAccess, \Countable
{
    private $array;

    public function __construct(array $array)
    {
        // keyが連番の数字になることを強制する
        $this->array = array_values($array);
    }

    public function count(): int
    {
        return count($this->array);
    }

    /* IteratorAggregateインターフェースの実装 */

    public function offsetGet($offset)
    {
        return $this->offsetExists($offset) ? $this->array[$offset] : null;
    }

    /* ArrayAccessインターフェースの実装 */

    public function offsetExists($offset)
    {
        return isset($this->array[$offset]);
    }

    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->array[] = $value;
        } else {
            $this->array[$offset] = $value;
        }
    }

    public function offsetUnset($offset)
    {
        unset($this->array[$offset]);
    }

    public function getIterator(): ArrayIterator
    {
        return new ArrayIterator($this->array);
    }

}
2
0
2

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
2
0