dquh37673 2013-10-30 07:44
浏览 24
已采纳

迭代私有属性中的数组保持

I have the 'Article' class with the private property words which holds and array of Word class objects. I also have getWord method which can return one word:

class Article {
    private $words = Array(1 => new Word(1), 2 => new Word(2), ...);

    public function getWord($wordId) {
        if (array_key_exists($wordId, $this->words)) {
            return $this->words[$wordId];
        } else {
            return NULL;
        }
    }
}

I need to iterate through all exising words. What is the best way to do that?

Currently I'm returning all words as array using another method, but I don't think that is a good option.

  • 写回答

2条回答 默认 最新

  • dongshanya2008 2013-10-30 08:02
    关注

    If you want to iterate over an Article object, accessing all Word objects, you should implement either the Iterator interface, or IteratorAggregate.

    If this is done, iterating would be as easy as this:

    foreach ($article as $word) {
        // do stuff with Word object here
    }
    

    The easiest way would be to convert your existing getWords method. You could add a new method getIterator as required by the IteratorAggregate interface and implement it like this:

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

    If you want to get rid of getWords(), you could also pass the internal array directly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?