Help us understand the problem. What is going on with this article?

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

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);
    }

}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした