php - 缩小已实现方法的返回类型

标签 php oop php-7 return-type

我试图为返回类 B 实例的类 A 和类 B 本身指定两个接口(interface)。

我在接口(interface)上声明返回类型。

假设我有两个接口(interface)。

某种 RepositoryInterface,它有一个 get() 方法,该方法返回实现 ElementInterface 的对象

<?php

namespace App\Contracts;

interface RepositoryInterface {

    public function get( $key ) : ElementInterface;

}

还有一个元素界面:

<?php

namespace App\Contracts;

interface ElementInterface { }

现在,我的存储库实现声明了一个返回类型,它是特定类 MyElement

<?php

namespace App\Repositories;

class MyRepository implements RepositoryInterface {

    public function get( $key ) : MyElement {
        // ...
    }

}

其中MyElement是一些实现ElementInterface的类。

...这会导致 fatal error :

Declaration of MyRepository::get( $key ): MyElement must be compatible with RepositoryInterface::get( $key ): ElementInterface

如果我不在接口(interface)上指定返回类型,这将工作得很好。然而,我想限制任何实现 RepositoryInterface 的类返回的类的类型。

  1. 这在 PHP 7.1 中是不可能的吗?
  2. 如果这确实不可能,是因为我的模式不正确吗?
  3. 如何声明接口(interface)方法的返回类型而不指定该类型的实际实现。

最佳答案

对于任何低于 7.4 的 PHP 版本,这是不可能的。

如果您的界面包含:

public function get( $key ) : ElementInterface;

那么你的类(class)需要是:

class MyRepository implements RepositoryInterface {

    public function get( $key ) : ElementInterface {

        returns new MyElement();
        // which in turn implements ElementInterface
    }
}

实现接口(interface)的类的声明必须完全匹配接口(interface)制定的契约。

通过声明它必须返回特定的接口(interface)而不是特定的实现,您可以为如何实现它提供回旋余地(现在您可以返回 MyElementAnotherElement 只要两者都实现了 ElementInterface);但方法声明无论如何都必须相同。

查看它的工作情况 here .


从 PHP 7.4 开始,将于 2019 年 11 月发布,covariance will be supported for return types 。到那时,这就可以了。

关于php - 缩小已实现方法的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49352636/

相关文章:

php - 使用一个提交按钮一次在 mysql 表中进行多个输入

oop - Doctrine2 ORM 不会保存对 DateTime 字段的更改

ruby-on-rails - 在 Ruby on Rails 中使用 send 有什么好处?

yaml - PHP7 中的 PECL yaml

PHP 删除所有包含给定字符串的文件

php - 充电 前一个变量

php - 如何将 jQuery 语句应用于在运行时加载的元素?

php - 检查网站是否在阻止列表中

phalcon - PHP fatal error : Class 'jsonserializable' not found in Unknown on line 0

php - 使用 PHP7 时,是否需要用 PHPDoc 记录方法?