8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでObjectをforeachする

Posted at

objectをforeachするときのあれ。

Objectのforeach

基本的にはオブジェクトはforeach出来る

通常Objectにforeachをかけると可視性の範囲でプロパティが舐められる。

つまり

インスタンス化したオブジェクトをforeach
: public プロパティがイテレート!!

クラス内部のオブジェクトコンテキストで$thisをforeach
: 内部定義の全プロパティ&継承されたpublic,protectedプロパティ

インターフェイスの実装

 Iteratorインターフェイスを実装するとforeachの挙動をあれ出来る。でもこれ、実際問題面倒。

 クラス内部に舐めたい配列が有るならIteratorAggregateインターフェイスの実装で足る。

class Item_Box implements \IteratorAggregate
{
    public $container = [];

    public function getIterator()
    {
        return new \ArrayObject($this->container);
    }
}

IteratorAggregateの実装はgetIteratorの実装のみでたる。ココで注意しないと行けないのは返り値。
getIteratorはイテレータブルな値をreturnしなければならないが、
単純に配列をreturnしても駄目。

なのでここに配列を返したい場合にはArrayObjectでラップする必要がある。

ほかほか

 Generatorとかも気軽にforeachできるみたいだけど、その辺はまた後ほど(ローカルに5.5入ってない)

8
6
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
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?