PHPDoc可选参数

34

这里在SO上已经有两个类似的问题,但是没有一个答案似乎有效。

PHPDoc似乎不能将我的函数中的可选参数识别为可选的,例如:

/**
 * Opens the connection and sets encoding
 * 
 * @param string $encoding Encoding.
 */
public function __construct($encoding='UTF-8') 
{
    $this->connect_mysqli();
    $this->set_encoding_mysqli($encoding);
}

我觉得应该把$encoding标记为可选的,或者是我哪里出了问题?我真的尝试过使用谷歌和阅读文档,但我找到的只有:

  

如果您没有在实际代码中指示参数是可选的(通过“$paramname ='默认值'”),则应在参数的描述中提到该参数是可选的。

所以我认为我的代码没问题,但是在文档中我看到的是:"__construct(string $encoding)",没有任何迹象表明参数是可选的。

2个回答

43

严格来说,PHP 不支持“可选参数”,但是支持带有默认值的参数,这些参数在函数或方法调用时可以省略。好吧,这实际上就是一个可选参数,但是您

@param string $encoding Encoding.

这里完全正确,因为默认值是字符串。文档试图告诉你的是,你应该像这样自己提及:

@param string $encoding (optional) Encoding.

我同意你的观点,认为像

__construct([$encoding])
或者
__construct($encoding = 'UTF-8')

如果你发现了问题,非常好。你可以提交一个错误报告。

https://github.com/phpDocumentor/phpDocumentor2/issues?state=open

更新:意识到这已经在 https://github.com/phpDocumentor/phpDocumentor2/search?q=optional&type=Issues 中提到了。


好的,我的错。我以为PHPDocumentor已经内置了这个功能,并且认为我做错了什么。如果没有人很快出现并提供新信息,我会保持开放状态,否则我会接受你的答案。谢谢 - user2742648
4
PHPDocumentor 最新版本已添加支持。请参见 https://github.com/siad007/template.clean/commit/fe6f9c9b09799299e15b0a5c33c6325068de9609。 - techdude
3
这个能否使用新的注释进行更新?这里给出的链接都没有明显的答案。 - oskarth

0
如果你正在搜索 @method - 设置默认值:
@method static where(array|string $array, $string = '', $string1 = '')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接