使用phpdoc在子类中记录继承的函数/变量


Documenting inherited functions/variables in subclasses with phpdoc

假设我有一个带有一些变量的父类,它有phpdoc:

class Parent
{
    /**
     * This variable stores some important value that
     * is going to be changed in child classes
     * @var integer
     */
    public $variable = 0;
}

现在我正在编写子类,它覆盖了以下变量:

class Child extends Parent
{
    public $variable = 10;
}

所以我的问题是:我应该为Child类中的$variable编写什么phpdoc,这样我就不必复制和粘贴变量描述了?同样的问题也适用于方法。非常感谢您的帮助。

更新:我在创建phpdoc后看到错误后问了这个问题,比如Child类中的"没有属性$variable的摘要"。如果我添加这个摘要,错误就会消失,但phpdoc无论如何都会显示Parent类的描述,无论我在Child类中写什么。我做错了什么?

对我来说,这种行为听起来像是一个bug。子类属性上完全缺少docblock应该会导致父属性docblock被完全继承。请在github回购中将其作为问题进行报告。

您可以在类成员上使用@inheritdoc,如常量、属性、方法。。。它们可以从接口、父类、特性等继承。。。

示例:

interface MyInterface {
  
  /**
   * My doc
   *
   * @param string $myParam
   *
   * @return string|null
   */
  public function myMethodToImplement( string $myParam ) : ?string;
  
}
abstract class MyParentClass {
  
  /**
   * My inherited doc
   *
   * @param string $myParam
   *
   * @return string|null
   */
  public function myInheritedMethod( string $myParam ) : ?string {}
  
}

class MyClass extends MyParentClass implements MyInterface {
  
  /**
   * @inheritdoc
   */
  public function myInheritedMethod ( string $myParam ) : ?string {
    return parent::myInheritedMethod( $myParam );
  }
  
  
  /**
   * @inheritDoc
   *
   * @param bool $addedParam An added param
   *
   * You can add tags and still inherit from parent doc
   *
   * @throws NotImplementedException
   */
  public function myMethodToImplement ( string $myParam, bool $addedParam = false) : ?string {
    throw new NotImplementedException( __METHOD__ );
  }
}

有了像PHPStorm这样的IDE,我可以自动完成工作,也可以快速文档化。如果我用PHPDocument生成这个代码的文档,它也能工作。