Rom*_*sov 3 php oop interface extending-classes
子类是否无法实现相同的接口父类实现的正常行为?我得到了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
Run Code Online (Sandbox Code Playgroud)
编辑:所以上面的代码工作很好没有错误或警告,即使我blueprint在子类中实现接口two没有方法impement_me()为什么子类不能实现相同的接口父类实现?
如果我实现除了blueprint类之外的其他接口two然后它工作,我必须使用blueprint_new类内部的方法,two否则触发致命错误.这部分按预期工作.
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.
Run Code Online (Sandbox Code Playgroud)
子类自动继承父类的所有接口.
有时您不希望这样,但您仍然可以在子类中实现任何甚至多个接口.
唯一不起作用的是扩展接口,就像无法实现类(或抽象类)一样.
在第二个代码中触发的错误是因为你没有blueprint_new在类中实现接口的所有方法two,但基本上你的代码没有任何问题.
例:
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
Run Code Online (Sandbox Code Playgroud)