如果方法重写并返回父方法的结果,则 @return 标记的约定是什么?



如果我在某个类中有一个返回布尔值的方法,例如

class A {
  /**
   * This method doesn't do much
   * @return boolean
   **/
  public function a() {
    // Do something 
    // ... 
    return true;
  }
}

然后我有另一个方法覆盖这个方法,然后调用父方法并返回父方法的结果:

class B extends A {
  /**
   * @Override
   * This method just does some extra work, before handing
   * it over to class A's method 
   * @return what? 
   **/
  public function a() {
    // Do some extra stuff 
    // ... 
    // Then hand it over to the parent 
    return parent::a();
  }
}

列出B::a()的返回值的最佳(常规)值是什么?它应该说它返回boolean,还是返回"父节点的值",并参考父节点的文档?还是别的什么?

从编写的角度来看,第二个似乎更合理,因为,如果父元素的返回值发生了变化,它并不意味着文档的其他部分也会发生变化。从阅读的角度来看,第一种方法似乎更方便,更容易得到答案。

我认为这取决于你或你的团队:)

所以写

是可以的
/**
 * @return boolean
 */

表示B类,或者直接使用next标签:

/**
 * {@inheritdoc}
 */

这意味着方法与父方法具有相同的描述。http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_tags.inlineinheritdoc.pkg.html

在B中存在函数a()是没有意义的

public function a() {
    // Do some extra stuff 
    // ... 
    // Then hand it over to the parent 
    return parent::a();
}

因为当有B的实例时,它实际上有一个函数a(),它引用了它的父方法a()

顺便说一下,当你定义一个重写父类方法的函数时,你最好在它的docblock中提供你的文档。因为你可能会有一个不同的返回值或者做一些其他的事情

最新更新