Skip to Main Content
PHP 5 Kochbuch, Third Edition
book

PHP 5 Kochbuch, Third Edition

by David Sklar, Adam Trachtenberg, Carsten Lucke, Matthias Brusdeylins, Ulrich Speidel, Stephan Schmidt
September 2009
Intermediate to advanced content levelIntermediate to advanced
912 pages
48h 11m
German
O'Reilly Verlag
Content preview from PHP 5 Kochbuch, Third Edition

8.3 Einen eigenen Iterator implementieren

Problem

Sie wollen eine Reihe von Werten aus einem Objekt in einer foreach-Schleife auslesen. Die Werte sind aber nicht in einer Array-Eigenschaft gespeichert. Zum Beispiel wollen Sie die Werte erst zum Zeitpunkt der Iteration berechnen. Beispiel: Sie wollen die Namen der nächsten fünf Tage ausgeben.

Lösung

Implementieren Sie das Iterator-Interface, bestehend aus den Methoden rewind(), valid(), next(), key() und current():

class DayIterator implements Iterator{ public $n; // Zahl der auszugebenden Tage public $today; private $days = array( 0 => "Sonntag", 1 => "Montag", 2 => "Dienstag", 3 => "Mittwoch", 4 => "Donnerstag", 5 => "Freitag", 6 => "Samstag" ); private $currentDay; private $daysLeft; function __construct($n ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP programmieren unter Windows

PHP programmieren unter Windows

Arno Hollosi
CSS Kochbuch, 3rd Edition

CSS Kochbuch, 3rd Edition

Joergen Lang, Christopher Schmitt

Publisher Resources

ISBN: 9783868993271Purchase book