正如您所认识到的,实现接口在您的情况下是不够的。扩展缺乏灵活性。所以最好的方法是使用特质。
就我个人而言,我会结合特质和界面。它们易于使用,并且可以很好地扩展/实现其他功能。例子:
特质
trait MyTestTrait
{
public function registerParent($parent){
if(count($this->parents) >0){
throw new Exception("Closed Reference Loop");
}
$this->parents[] = $parent;
}
public function checkLoop($child){
if($child===$this){
throw new Exception("Closed Reference Loop");
}
foreach($this->parents as $parent){
$parent->checkLoop($child)
}
}
}
界面
interface MyTestInterface
{
public function registerParent($parent);
public function checkLoop($child);
}
课堂使用情况
class Object extends SomeAbstract implements MyTestInterface, AnotherInterface {
use MyTestTrait;
$contents = array();
$parents = array();
function add($content){
if(is_a($content, "Container")){
$content->registerParent($this);
$this->checkLoop($content);
$this->contents[] = $content;
}
}
}
多亏了接口,我们可以确定registerParent()和checkLoop()方法都存在。由于这个特性,我们在不影响类扩展能力的情况下实现了它们。干杯