note 117875 added to class.iteratoraggregate

From: Date: Mon, 24 Aug 2015 23:21:59 +0000
Subject: note 117875 added to class.iteratoraggregate
Groups: php.notes 
Request: Send a blank email to php-notes+get-203457@lists.php.net to get a copy of this message
Example of the Iterator Pattern <?php namespace DesignPaterns; class BookCollection implements \IteratorAggregate { private $a_titles = array(); public function getIterator() { return new BookIterator($this); } public function addTitle($string) { $this->a_titles[] = $string; } public function getTitle($key) { if (isset($this->a_titles[$key])){ return $this->a_titles[$key]; } return null; } public function is_empty() { return empty($a_titles); } } <?php namespace DesignPaterns; class BookIterator implements \Iterator { private $i_position = 0; private $booksCollection; public function __construct(BookCollection $booksCollection) { $this->booksCollection = $booksCollection; } public function current() { return $this->booksCollection->getTitle($this->i_position); } public function key() { return $this->i_position; } public function next() { $this->i_position++; } public function rewind() { $this->i_position = 0; } public function valid() { return !is_null($this->booksCollection->getTitle($this->i_position)); } } <?php require 'vendor/autoload.php'; use DesignPaterns\BookCollection; $booksCollection = new BookCollection(); $booksCollection->addTitle('Design Patterns'); $booksCollection->addTitle('PHP7 is the best'); $booksCollection->addTitle('Laravel Rules'); $booksCollection->addTitle('DHH Rules'); foreach($booksCollection as $book){ var_dump($book); } /* === Output === * string(15) "Design Patterns" * string(16) "PHP7 is the best" * string(13) "Laravel Rules" * string(9) "DHH Rules" */ ---- Server IP: 72.52.91.14 Probable Submitter: 89.153.221.218 ---- Manual Page -- http://php.net/manual/en/class.iteratoraggregate.php Edit -- https://master.php.net/note/edit/117875 Del: integrated -- https://master.php.net/note/delete/117875/integrated Del: useless -- https://master.php.net/note/delete/117875/useless Del: bad code -- https://master.php.net/note/delete/117875/bad+code Del: spam -- https://master.php.net/note/delete/117875/spam Del: non-english -- https://master.php.net/note/delete/117875/non-english Del: in docs -- https://master.php.net/note/delete/117875/in+docs Del: other reasons-- https://master.php.net/note/delete/117875 Reject -- https://master.php.net/note/reject/117875 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#203457) next »