特征 return 类型

Traits return type

我一直在尝试在 interface 中指定函数的 return 类型 PHP 是否缺少对此的支持或者我遗漏了什么?

<?php interface AInterface { public function F() : self; }

当我实现上面的 interface 时,以下会导致关于不匹配声明的致命错误:

<?php class A { public function F() : self { return $this; } }

编辑:我知道删除 interface 内部的 : self 可以修复错误,但这是否意味着无法确保使用接口的 return 类型?

你没有实现接口,而且你对使用有一些困惑self;

self does not refer to the instance, it refers to the current class.

这就是我想达到的目标:

<?php
/**
 * Created by PhpStorm.
 * User: kourouma
 * Date: 12/08/2018
 * Time: 17:35
 */
interface AInterface { public function F() : AInterface;}

class A implements  AInterface { public function F() : AInterface { return $this; }}

$a = new A();
var_dump($a->F()); // empty object

Return 类型声明 RFC 是这样说的:

The enforcement of the declared return type during inheritance is invariant; this means that when a sub-type overrides a parent method then the return type of the child must exactly match the parent and may not be omitted. If the parent does not declare a return type then the child is allowed to declare one.

...

Read more here 希望对你有帮助。