【问题标题】:How do I specify the type of an object returned by an inherited method in PHPDoc?如何指定 PHPDoc 中继承方法返回的对象类型?
【发布时间】:2015-03-09 19:12:15
【问题描述】:

假设我有这个抽象的数据库表类:

abstract class DbTable {
    /**
     * Table records
     * @var DatabaseRecordIF[] 
     */
   protected $records;

   /**
    * Returns the records.
    * @return DatabaseRecordIf[]
    */
   public function getRecords() {
       return $this->records;
   }
}

我有一个特定的数据库表类来存储表中的记录:

class MyTable extends DbTable { }

我有一个类在该表中定义了一条记录:

class MyTableRecord implements DatabaseRecordIf { }

我想告诉 phpDocumentor MyTable::getRecords() 返回 MyTableRecord[],而不仅仅是 DatabaseRecordIf[]。这可能吗?

有没有更好的方法来解决这个问题?

【问题讨论】:

  • @var 用于传递给方法的参数,@return 用于返回的数据类型

标签: php inheritance containers phpdoc


【解决方案1】:

phpDocumentor 定义了staticself 用于指定继承方法返回的类型。

self 使用此类型的类的对象,如果继承它仍将代表最初定义它的类。

static 使用此值的类的对象,如果继承它将代表子类。 (参见 PHP 手册中的后期静态绑定)。

所以 static 是您需要返回子类型而不是父类型的类型。

   /**
    * Returns the records.
    * @return static[]
    */
   public function getRecords() {
       return $this->records;
   }

【讨论】:

  • 嗯,我不确定这是后期绑定的情况。我在父类 (DbTable) 中定义了 getRecords()。子类 MyTable 无法知道其继承的 getRecords 最终会返回 MyTableRecord 对象。
猜你喜欢
  • 2017-01-10
  • 2014-07-26
  • 2016-05-08
  • 2010-12-20
  • 1970-01-01
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多