如何使用phpDoc重载方法?

Tom*_*rek 13 php overloading phpdoc documentation-generation

假设我有一个名为Color的PHP类,它的构造函数接受各种参数.

// hex color
$myColor = new Color('#FF008C');

// rgb channels
$myColor = new Color(253,15,82);

// array of rgb channels
$myColor = new Color(array(253,15,82));

// X11 color name
$myColor = new Color('lightGreen');
Run Code Online (Sandbox Code Playgroud)

我应该如何使用phpDoc为构造函数和其他类似的方法创建API文档?

如何使用phpDoc重载方法?

class Color {

    /**
     * Constructor
     * what should be here?
     */
    public function __construct() {
        /* CODE */
    }

}
Run Code Online (Sandbox Code Playgroud)

min*_*.dk 18

只是我的观点,但你不应该首先有多个构造函数 - 你的构造函数将充满if/else-ladder,这真的不是一个好主意,特别是对于轻量级的东西,如表示颜色.

我强烈建议您尝试这样的事情:

class Color
{
    protected function __construct($r, $g, $b)
    { ... }

    public static function fromHex($hex) {
        return new Color(...);
    }

    public static function fromRGB($r, $g, $b) { ... }

    public static function fromArray(array $rgb) { ... }

    ...
}
Run Code Online (Sandbox Code Playgroud)

现在,在消费者代码中,而不是像这样的一些神秘和模糊的构造函数调用:

$a = new Color(0,0,0);
$b = new Color('#000000');
Run Code Online (Sandbox Code Playgroud)

相反,您可以拥有更易读和语义的消费者代码,如下所示:

$a = Color::fromRGB(0,0,0);
$b = Color::fromHex('#000000');
Run Code Online (Sandbox Code Playgroud)

这对于阅读消费者代码的人来说可能更有意义,它消除了使模糊构造函数工作所需的逻辑,并且作为奖励(如果您使用的是诸如PhpStorm之类的IDE),您可以通过所有检查.如果您正在运行文档生成器,这也可以确保所有选项都单独记录,而不是在口头描述中集中在一起.

请注意,我声明了构造函数protected- 这是个人偏好,但是如果我要使用多个静态工厂方法,我更愿意看到那些在消费者代码中一直使用的方法,而不是有时看到Color::fromRGB(...)和其他时间new Color(...).

  • 这个答案值得更多的赞誉,因为它促进了更好的编程实践. (2认同)

Rom*_*kiy 7

我认为最好@method为类/接口使用注释,它声明了重载方法.这个问题对我来说也很有趣.

 /**
  * @method void setValue(int $value)
  * @method void setValue(string $value)
  * @method void setValue(string $value, int $startFrom)
  */
 class Example
 {
     public function setValue($arg1, $arg2)
     {
        // ...
     }
 }
Run Code Online (Sandbox Code Playgroud)

http://phpdoc.org/docs/latest/references/phpdoc/tags/method.html


Ste*_*iec 4

因为您允许可变长度参数,所以我可以通过两种方法来执行此操作。

我只想列出允许的参数是参数。

/**
 * @param mixed $arg1 ... description
 * @param mixed $arg2 ... description
 * @param mixed $arg3 ... description
 */
 public function __construct() {}
Run Code Online (Sandbox Code Playgroud)

或者我会简单地用一些例子来解释。

/**
 * Explanation of different expected argument combinations.
 */
public function __construct() {}
Run Code Online (Sandbox Code Playgroud)

另一种选择是,由于只有一个示例具有多个参数,因此只需在方法签名中定义参数,使最后 2 个参数成为可选。像这样:

/**
 * @param mixed $arg1 ...
 * @param int $arg2 ...
 * @param int $arg3 ...
 */
public function __construct($arg1, $arg2 = null, $arg3 = null) {}
Run Code Online (Sandbox Code Playgroud)

  • 这是旧的,但只是为了提供一个替代方案供参考 - 你也可以只说“@param mix $args ...代表 blah blah 的可变数量的参数” (2认同)