PHP OOP接口类型继承


PHP OOP Interface typing inheritance

像这样的代码:

interface entite
{
}
class Foo implements entite
{
}

$foo = new foo;
if( $foo instanceof entite ) echo "he is";

显示"he is"。Foo从接口继承"entite"类型但是当你尝试:

class FooDeleter implements deleter
{
public function __construct(Foo $Foo)
{
}
}
interface deleter
{
public function __construct(entite $entite);
}

给我:

Fatal error: Declaration of FooDeleter::__construct() must be compatible with deleter::__construct(entite $entite)

为什么?怎么做?= (

编辑:唯一的方法实际上是像这样定义类型化删除器:

class FooDeleter implements deleter
{
public function __construct(entite $Foo)
{
    if( $Foo instanceof Foo ) { ... }       
}
}

通过使用比接口更严格的类型提示声明FooDeleter构造函数,您违反了接口。

如果你把构造函数改成

public function __construct(entite $Foo)

…那么你仍然可以传入一个Foo对象,并且接口将被正确实现。

根据PHP文档:

注意:

实现接口的类必须使用与接口中定义的完全相同的方法签名。不这样做将导致致命错误。

函数名、参数号和参数类型(如果指定的话)是方法签名的一部分(全部?),所以你必须声明一个完全相同的方法。

您仍然可以使用new FooDeleter($foo)