DocBlock 类类型继承

Chr*_*ian 4 php javadoc phpdoc docblocks

虽然这个问题一般是关于DocBlocks的,但我的用例是关于 PHP。

考虑以下 PHP 代码:

<?php

class ParentClass {
    /**
     * Says 'hi' to the world.
     * @return ParentClass Returns itself for chaining.
     */
    public function say_hi(){
        echo 'hi';
        return $this;
    }
}

class ChildClass extends ParentClass {
    /**
     * Says 'bye' to the world.
     * @return ChildClass Returns itself for chaining.
     */
    public function say_bye(){
        echo 'bye';
        return $this;
    }
}

$c = new ChildClass;
$c->say_hi()->say_b| <- type hinting won't suggest "say_bye" here

?>
Run Code Online (Sandbox Code Playgroud)

这只是一个带有一些链接的琐碎类。扩展类没有类型提示,因为父类的文档块正在使用特定的类名,该类名没有子类的方法/属性。

假设我们确实想要类型提示功能,(如果没有,请留下这个问题 - 我不想要无用的参数),我应该如何解决这个问题?

我想出了以下可能性:

  • 更改 PHPDoc 标准以允许使用特殊关键字
  • 添加一个多余的 say_hi() 方法,该方法调用父级只是为了重新声明 docblock
  • 根本不指定返回类型,让 IDE 决定什么return $this;意思(这甚至有效吗?)

小智 5

你可以这样解决:

class ParentClass {
    /**
     * Says 'hi' to the world.
     * @return static
     */
    public function say_hi(){
        echo 'hi';
        return $this;
    }
}
Run Code Online (Sandbox Code Playgroud)

“@return static”语句完全符合您的要求,PhpStorm 可以很好地使用它。