【问题标题】:PHP OOP Interface typing inheritancePHP OOP 接口类型继承
【发布时间】:2013-02-19 07:16:04
【问题描述】:

这样的代码:

interface entite
{

}

class Foo implements entite
{

}


$foo = new foo;
if( $foo instanceof entite ) echo "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 ) { ... }       
}
}

【问题讨论】:

  • 希望你的意思是“OOP 接口”?
  • 这是来自 PHP Big Brown Book 的示例代码。
  • 我很惊讶 PHP 允许您在接口中定义构造函数。对我来说似乎是一个可怕的想法。相关问题在这里 - stackoverflow.com/questions/783046/…
  • @Phil 这确实看起来像是一个无用的功能。
  • Actor 是一个实现细节,不应进入接口。

标签: php oop interface inheritance


【解决方案1】:

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

如果您将构造函数更改为

public function __construct(entite $Foo)

...那么您仍然可以传入Foo 对象,并且接口将正确实现。

【讨论】:

    【解决方案2】:

    根据PHP Document

    注意

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

    函数名称和参数编号以及参数类型(如果指定)是方法签名的一部分(全部?),因此您必须声明完全相同的方法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-12
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多