PMG Digital Made for Humans

Making Traversable Interfaces the Right Way

2 MINUTE READ | April 21, 2015

Making Traversable Interfaces the Right Way

Author's headshot

Christopher Davis

Christopher Davis has written this article. More details coming soon.

In PHP, objects that implement Traversable can be used in foreach loops. Traversable can’t be implemented directly in userland (pure PHP) code and instead Iterator or IteratorAggregate have to be used.

But what if you’re defining an interface that’s iterable as part of its contract? Should your interface extend Iterator or IteratorAggregate?


<?phpinterface Foo extends \Iterator{    // ...}interface Bar extends \IteratorAggregate{    // ...}

Neither. Instead interfaces should extend Traversable directly.


<?phpinterface Spam extends \Traversable{    // ...}

Since interfaces should be, for the most part, role based the clients of an interface shouldn’t care that Iterator or IteratorAggregate is used. They just care that they can iterate over an object.

Extending Traversable means that it’s up to the implementing class to choose the best way to accomplish its iteration. Just like it should be.

To implement an interface that extends traversable, the implementing class’s implements declaration should include Iterator or IteratorAggregate. The trick here is the ordering: Iterator or IteratorAggregate must come first.


<?phpinterface Spam extends \Traversable{    // ...}final class Ham implements \IteratorAggregate, Spam{    public function getIterator()    {        return new \ArrayIterator(range(1, 10));    }}

Doing otherwise causes an error on PHP (but seems to work okay on HHVM).


Stay in touch

Bringing news to you

Subscribe to our newsletter

By clicking and subscribing, you agree to our Terms of Service and Privacy Policy

<?phpinterface Spam extends \Traversable{    // ...}final class Ham implements Spam, \IteratorAggregate{    public function getIterator()    {        return new \ArrayIterator(range(1, 10));    }}

Related Content

thumbnail image

AlliPMG CultureCampaigns & Client WorkCompany NewsDigital MarketingData & Technology

PMG Innovation Challenge Inspires New Alli Technology Solutions

4 MINUTES READ | November 2, 2021

thumbnail image

Applying Function Options to Domain Entities in Go

11 MINUTES READ | October 21, 2019

thumbnail image

My Experience Teaching Through Jupyter Notebooks

4 MINUTES READ | September 21, 2019

thumbnail image

Working with an Automation Mindset

5 MINUTES READ | August 22, 2019

thumbnail image

3 Tips for Showing Value in the Tech You Build

5 MINUTES READ | April 24, 2019

thumbnail image

Testing React

13 MINUTES READ | March 12, 2019

thumbnail image

A Beginner’s Experience with Terraform

4 MINUTES READ | December 20, 2018