PHP 子类不能实现相同的接口(interface)父类实现

标签 php oop interface extending-classes

子类不能实现父类实现的相同接口(interface)是正常行为吗?我得到了 PHP v5.6

interface blueprint {
    public function implement_me();
}

class one implements blueprint {

    public function implement_me() {

    }

}

class two extends one implements blueprint {


}

//no fatal error triggered for class two 

编辑: 所以即使我在子类 two 中实现了接口(interface) blueprint 而没有方法 ,上面的代码也没有错误或警告>impement_me() 为什么子类不能实现父类实现的相同接口(interface)?

如果我为类 two 实现了除 blueprint 之外的另一个接口(interface),那么它就可以工作,我必须在类 中使用 blueprint_new 方法两个 否则会触发 fatal error 。这部分按预期工作。

interface blueprint {
    public function implement_me();
}

class one implements blueprint {

    public function implement_me() {

    }

}


interface blueprint_new {
    public function todo();
}


class two extends one implements blueprint_new {


}

//this will trigger fatal error.

最佳答案

子类自动继承父类的所有接口(interface)。

有时您不希望这样,但您仍然可以在子类中实现任何,甚至多个接口(interface)。

唯一不行的就是扩展一个接口(interface),就像一个类(或者抽象类)不能实现一样。

你的第二个代码中触发的错误是因为你没有在类two中实现接口(interface)blueprint_new的所有方法,但基本上你的代码没有错。

例子:

class MobilePhone implements GsmSignalPowered {}
class SamsungGalaxy extends MobilePhone implements UsbConnection {}
interface ThunderboltPowered {}
interface GsmSignalPowered {}
interface UsbConnection {}

$s = new SamsungGalaxy();
var_dump($s instanceof GsmSignalPowered); // true
var_dump($s instanceof UsbConnection); // true
var_dump($s instanceof ThunderboltPowered); // false

$m = new MobilePhone();
var_dump($m instanceof GsmSignalPowered); // true
var_dump($m instanceof UsbConnection); // false
var_dump($m instanceof ThunderboltPowered); // false

关于PHP 子类不能实现相同的接口(interface)父类实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40334866/

相关文章:

php - 需要有关在 MySQL 数据库中提交 html 表单的帮助吗?

php - Yii2登录无密码验证

php - 通过ajax返回javascript但它不起作用

oop - 无法将构造函数定义为绑定(bind)函数

php - 循环遍历多维数组

java - 不要在子类的构造函数中创建父类(super class)实例,但完全合法

java - 我如何用 int 数组编写获胜方法

java - 对类型 `List<Iterable<Object>>` 的列表进行排序

java - 用于构建对象的通用验证和转换链的代码

c# - 接口(interface)的IL代码