我希望拥有符合接口(interface)的可迭代对象,但希望将如何实现可迭代性的选择(例如实现 Iterator
或 IteratorAggregate
)留给实现。
我认为这可能会起作用:
interface IsTraversable extends Traversable {
// some other stuff here
}
class A implements IsTraversable, IteratorAggregate {
function getIterator() {
return new ArrayIterator(array());
}
}
但它抛出:
Class A must implement interface Traversable as part of either Iterator or IteratorAggregate
随着 IteratorAggregate
的实现,该消息有点令人困惑。它似乎试图告诉我,我无法直接实现 Traversable
。
可以实现我的要求吗?
最佳答案
如果扩展Traversable
,则需要在实现列表中首先列出IteratorAggregate
。根据 PHP manual :
This is an internal engine interface which cannot be implemented in PHP scripts. Either IteratorAggregate or Iterator must be used instead. When implementing an interface which extends Traversable, make sure to list IteratorAggregate or Iterator before its name in the implements clause.
强调我的。这不会引发错误:
<?php
interface IsTraversable extends Traversable {
// some other stuff here
}
class A implements IteratorAggregate, IsTraversable {
function getIterator() {
return new ArrayIterator(array());
}
}
关于php - 是否可以实现一个扩展 Traversable 的接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46141903/