如何使用phpDoc重载方法?

时间:2009-08-28 19:17:25

标签: php overloading documentation-generation phpdoc

假设我有一个名为 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');

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

如何在重载方法中使用phpDoc?

class Color {

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

}

4 个答案:

答案 0 :(得分: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) { ... }

    ...
}

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

$a = new Color(0,0,0);
$b = new Color('#000000');

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

$a = Color::fromRGB(0,0,0);
$b = Color::fromHex('#000000');

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

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

答案 1 :(得分: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)
     {
        // ...
     }
 }

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

答案 2 :(得分:4)

因为你允许变长参数,我有两种方法可以做到这一点。

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

/**
 * @param mixed $arg1 ... description
 * @param mixed $arg2 ... description
 * @param mixed $arg3 ... description
 */
 public function __construct() {}

或者我只是提供一些例子的解释。

/**
 * Explanation of different expected argument combinations.
 */
public function __construct() {}

另一种选择,因为只有一个例子有一个以上的参数,就是简单地在方法签名中定义参数,使最后两个可选。像这样:

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

答案 3 :(得分:1)

我知道用phpDoc做这个没有优雅的方法。 phpDoc评论/ api格式基于Javadoc格式。 Javadoc没有支持此功能的功能集,因为在java中,如果您希望方法具有可变数量的参数,则需要为每个变体重新声明方法原型。

public double foo() {
}

public double foo(double my_param) {        
}

所以,我的表现偏好是做类似

的事情
/**
 * My General description
 * 
 * Here explain what each argument combination can do
 * @param mixed $arg1 can be array, string, hex as string, or int 
 * @param int $arg2 if arg1 is int, then this is etc, otherwise optional 
 * @param int $arg3 if ar1 is int, then this is etc, otherwise optional
 */

但这可能不适合各种自动文档工具。

根据霍伊尔的方式来实现这一点可以在phpDoc site找到。