menu

Questions & Answers

Iterative as a trait with Traversable

I want to create PHP's Iterators using my trait named Iterative. I tried to do this in this way:

  1. Trait Iterative "implements" interface Traversable

     trait Iterative
     {
         public function rewind(){ /* ... */ }
         public function current(){ /* ... */ }
         public function key(){ /* ... */  }
         public function next(){ /* ... */ }
         public function valid(){ /* ... */ }
     }
    
  2. Class BasicIterator should implement the interface using trait

     class BasicIterator implements \Traversable {
         use Iterative;
     }
    

but i get:

    Fatal error: Class BasicIterator must implement interface Traversable as part of either Iterator or IteratorAggregate in Unknown on line 0

Is it even possible and in what way?

Comments:
2023-01-18 23:01:19
I don't think you can use the Traversable interface like that. php.net/manual/en/class.traversable.php
Answers(2) :

The problem is not with using Traits, but because you are implementing the wrong interface. See this note on the manual page for Traversable:

This is an internal engine interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead.

Write class BasicIterator implements \Iterator instead, since that is the interface whose methods you have included in your Trait.

I believe you must implement either Iterator, or IteratorAggregate, eg:

<?php
trait Iterative
{
    public function rewind(){ /* ... */ }
    public function current(){ /* ... */ }
    public function key(){ /* ... */  }
    public function next(){ /* ... */ }
    public function valid(){ /* ... */ }
}

# Class BasicIterator should implements the interface using trait

class BasicIterator implements \Iterator {
    use Iterative;
}
?>

see http://3v4l.org/G7KiF