【问题标题】:How to extend interface in PHP and keep backward compatibility?如何在 PHP 中扩展接口并保持向后兼容性?
【发布时间】:2015-03-03 07:35:19
【问题描述】:

我们有一些遗留接口代码,我想在不破坏实现它的其他类的情况下对其进行扩展。我需要向其中一种接口方法添加附加参数,以便实现该接口的新类将使用而旧类将忽略它。 AFAIK,如果不更改实现方法签名,就无法更改接口。

当前实现:

interface inter
{
    public function hey($rr);
}

class Cl implements inter
{
    function hey($rr) {
        echo "hey";
    }
}

我想要这样的东西:

interface inter
{
    public function hey($rr, $ee = true);
}

class Cl implements inter
{
    function hey($rr) {
        echo "hey";
    }
}

我知道这会导致致命错误 - 我想了解这种情况是否有类似的方法或最佳实践。

谢谢, 阿隆

【问题讨论】:

    标签: php design-patterns interface


    【解决方案1】:

    我认为不存在任何解决方案。我建议添加另一种具有不同名称的方法,例如

    interface inter
    {
        public function hey($rr);
        public function yey($rr, $ee = true);  
    }
    

    或者更好地扩展接口与另一个适用于新类的接口。

    interface other_inter extends inter
    {
        public function yey($rr, $ee = true);  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-17
      • 1970-01-01
      相关资源
      最近更新 更多