抽象父类已经实现的请求接口因类型安全而失败

时间:2019-07-03 11:21:22

标签: inheritance interface abstract-class php-7.1

我想定义接口方法ImplementedInterface()的返回类型,返回接口本身(AI)(例如流利的setter),继承供应商类,该类实现了所请求的接口并且已经具有返回类型-但是在以下情况下似乎是不可能的。 也许这是不可能的,但如果不是这样,什么是有效的解决方案?

此示例有效:

<?php
declare(strict_types=1);

/**
 * This interface is defined by the user
 */
interface AI
{
    public function implementedInterface();
}

/**
 * This class is immutable because it is vendor
 */
abstract class A
{
    public function implementedInterface(): self
    {
        return $this;
    }
}

/**
 * This class is defined by the user
 */
class B extends A implements AI
{
}

这是我想要的方法,但是结果是: PHP Fatal error: Declaration of A::implementedInterface() must be compatible with AI::implementedInterface(): AI

<?php
declare(strict_types=1);

/**
 * This interface is defined by the user
 */
interface AI
{
    public function implementedInterface(): AI;
}

/**
 * This class is immutable because it is vendor
 */
abstract class A
{
    public function implementedInterface(): self
    {
        return $this;
    }
}

/**
 * This class is defined by the user
 */
class B extends A implements AI
{
}

0 个答案:

没有答案