返回类型为"self"在抽象的PHP类中 [英] Return type "self" in abstract PHP class
问题描述
PHP 7.1
我目前正在尝试制作一个抽象类,以提供和定义并部分实现其子类的功能.
I'm currently trying to make an abstract class to provide and define and partially implement functionality of its' child classes.
在这里,我使用以下结构:
Here I use the following construct:
abstract class Parent {
public static function fromDB(string $name = '') {
$instance = new static();
if (!empty($name)) {
$instance->setName($name)->read();
}
return $instance;
}
public abstract function read();
public abstract function setName(string $name): self;
}
PHP似乎了解setName($name)
返回类型为Parent
的对象,但是PhpStorm指示无法在结果上调用read()
,这将是预期的结果.
Here PHP seems to understand that setName($name)
returns a Object with type Parent
, but PhpStorm indicates that read()
can not be called on the result, which would have been the expected result.
错误消息:在主题类中找不到引用的方法.
Error Message: Referenced Method is not found in subject class.
我不确定这是否是PHP或PhpStorm中的错误,或更可能是我不了解自己在做什么...
I'm not sure if this is a bug in PHP or PhpStorm, or, much more likely, me not understanding what I'm doing...
我已经阅读了后期静态绑定"以及以下部分讨论此问题的问题,但我不知道如何解决此问题:
I've read up on Late static binding and the following questions which partially talk about this problem, but I couldn't figure out how to fix it:
- Question 1
- Question 2
- Late Static Binding Doc
感谢您的时间和帮助.
编辑:如下所示,我正在尝试在子类中实现:
As hinted below, I'm trying to implement in child classes like:
public function setName(string $name = null): user {...}
显然不适用于self
返回,但是(IMO应使用)static
,这是被禁止的.
which obviously doesn't work with self
return but (IMO should) with static
, which is forbidden.
推荐答案
您的代码示例在 PhpStorm 2017.2 (当前处于EAP阶段)中看起来不错,但在2017.1.4中显示警告.
Your code sample looks fine in PhpStorm 2017.2 (currently in EAP stage) but shows warning in 2017.1.4.
很有可能是由 WI-33991 或其中一张相关票证所修复的.
Quite possibly it was fixed by WI-33991 or one of the related tickets.
您可能会得到&随时可以从此处尝试2017.2 EAP构建: http://confluence. jetbrains.com/display/PhpStorm/PhpStorm+Early+Access+Program
You may get & try the 2017.2 EAP build at any time from here: http://confluence.jetbrains.com/display/PhpStorm/PhpStorm+Early+Access+Program
它具有自己的30天许可证,可以与当前版本并行运行(IDE范围的设置存储在单独的文件夹中).
It comes with own 30-days license and can run in parallel to your current version (IDE-wide settings are stored in separate folders).
这篇关于返回类型为"self"在抽象的PHP类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!