子类不能实现父类实现的相同接口(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),那么它就可以工作,我必须在类 中使用
否则会触发 fatal error 。这部分按预期工作。blueprint_new
方法两个
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/