interfaceの継承
interface A
{
public function a(string $a, int $b);
}
interface Foo extends A
{
}
これ、動きます。Fooはa()の実装を強制出来るinterfaceになりました。
interfaceの多重継承
interface A1
{
public function a(string $a, int $b);
}
interface A2
{
public function b(string $a, int $b);
}
interface Foo extends A1, A2
{
}
実はこれも動きます。
Fooは、a()とb()の実装を強制出来るinterfaceになりました。
多重継承で、同じメソッドを書いたら?
ではここでクイズ。
interface A1
{
public function a(string $a, int $b);
}
interface A2
{
public function a(string $a, int $b);
}
interface Foo extends A1, A2
{
}
class Hoge implements Foo {
public function a(string $a, int $b)
{
return true;
}
}
全く同じ関数名、同じ構成のものを多重継承したら?
これも動きます。ちゃんとHoge動きます。オーバーライドしてるっぽい?
多重継承で、同じメソッドを拡張するように書いたら?
interface A1
{
public function a(string $a, int $b);
}
interface A2
{
public function a(string $a, int $b): bool;
}
interface Foo extends A1, A2
{
}
class Hoge implements Foo {
public function a(string $a, int $b): bool
{
return true;
}
}
ではこれは?
なんと動きません。
PHP Fatal error: Declaration of A1::a(string $a, int $b) must be compatible with A2::a(string $a, int $b): bool in /workspace/Main.php on line 13
A1のメソッド、A2のメソッドの条件に一致していないってなってます。
つまり・・・?
仮設: 多重継承に読み込み順がある?
interface A1
{
public function a(string $a, int $b): bool;
}
interface A2
{
public function a(string $a, int $b);
}
interface Foo extends A1, A2
{
}
class Hoge implements Foo {
public function a(string $a, int $b): bool
{
return true;
}
}
なんと、これ動きます。
これは仮設ですが、A2をまず継承したあと、A1を定義しているのかもしれません。
A2の条件をA1のメソッドが満たしているので、これは正しく動きます。
ちなみに、関数名変えたり並び替えたりは試したので、クラス名は関係なさそうですφ(・・
まだまだPHPわからないことあって面白いですね(‘ω‘ )