2014年11月にリリースされたPHP7.4では、型の差異が改善されています。
質問のコードは無効のままです:
interface Item {
// some methods here
}
interface SuperItem extends Item {
// some extra methods here, not defined in Item
}
interface Collection {
public function add(Item $item);
// more methods here
}
interface SuperCollection extends Collection {
public function add(SuperItem $item); // This will still be a compile error
// more methods here that "override" the Collection methods like "add()" does
}
インターフェイスは、それを実装するすべてのものがのパラメータとしてCollection
タイプの任意のオブジェクトを受け入れることができることを保証するためです。Item
add
ただし、次のコードはPHP7.4で有効です。
interface Item {
// some methods here
}
interface SuperItem extends Item {
// some extra methods here, not defined in Item
}
interface Collection {
public function add(SuperItem $item);
// more methods here
}
interface SuperCollection extends Collection {
public function add(Item $item); // no problem
// more methods here that "override" the Collection methods like "add()" does
}
この場合Collection
、それが任意のを受け入れることができることを保証しますSuperItem
。すべてSuperItem
のsはItem
sでSuperCollection
あるため、他のタイプのを受け入れることができることも保証しながら、この保証も行いますItem
。これは、共変性メソッドのパラメーター型として知られています。
以前のバージョンのPHPには、限定された形式の型の差異があります。他のインターフェースが質問のとおりであると仮定すると、は次のSuperCollection
ように定義できます。
interface SuperCollection extends Collection {
public function add($item); // no problem
// more methods here that "override" the Collection methods like "add()" does
}
add
これは、メソッドに渡される可能性のあるすべての値を意味すると解釈できます。もちろん、これにはすべてItem
のが含まれるため、これはタイプセーフであるか、または一般に渡される可能性があるように文書化された不特定のクラスの値を意味すると解釈できmixed
、プログラマーは関数で何が機能するかについて他の知識を使用する必要があります。