强制 类 执行一组方法中的一个

Force classes to implement one of a set of methods

假设我需要一组 classes 来实现 所有方法 X、Y 和 Z 才能正常工作。在那种情况下,我可以让他们实现一个通用接口来强制执行此操作。

现在,我的情况有点不同 - 我的 classes 需要实现 至少 X、Y 和 Z 之一,不一定是全部。接口在这里帮不了我。我能想到的最接近的是一个常见的 parent - 它可以检查其构造函数中 X、Y 或 Z 的存在。

我宁愿在这里避免继承,因为我可能需要在已经有 parent 的 class 中实现这个 "interface"。那么 - 还有另一种优雅的方法吗?

(我在 PHP 工作,但如果存在通用的 OOP 解决方案,它可能会服务于更广泛的受众。)

I'd rather avoid inheritance here, because I may need to implement this "interface" in a class that already has a parent. So - is there another elegant way to do this?

如果我理解正确,你可以通过 Traits:

解决这个问题
trait DefaultImpl
{
    public function x()
    {
        echo "Default implementation of x()\n";
    }

    public function y()
    {
        echo "Default implementation of y()\n";
    }

    public function z()
    {
        echo "Default implementation of z()\n";
    }
}

class XImpl
{
    use DefaultImpl;

    public function x()
    {
        echo "Custom implementation of X\n";
    }
}

$x = new XImpl();
$x->x();
$x->y();
$x->z();

从设计的角度来看,这不是一个很好的解决方案。但这总比不必要的继承要好。