I want to make a PHP's Iterators using my trait named Iterative. I tried to do this in this way:
Trait Iterative "implements" interface Traversable
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 \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?
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;
}
?>