16. 代码注释

未匹配的标注

PHPDoc

PHPDoc 是注释 PHP 代码的非官方标准,有多种不同 标签 可供选择,标签和实例的完整列表可以在 PHPDoc manual 的操作手册中找到
下面是一个范例,说明如何对一个带有少量方法的类进行文档化:

<?php
/**
 * @author A Name <a.name@example.com>
 * @link http://www.phpdoc.org/docs/latest/index.html
 */
class DateTimeHelper
{
    /**
     * @param mixed $anything Anything that we can convert to a \DateTime object
     *
     * @throws \InvalidArgumentException
     *
     * @return \DateTime
     */
    public function dateTimeFromAnything($anything)
    {
        $type = gettype($anything);

        switch ($type) {
            // Some code that tries to return a \DateTime object
        }

        throw new \InvalidArgumentException(
            "Failed Converting param of type '{$type}' to DateTime object"
        );
    }

    /**
     * @param mixed $date Anything that we can convert to a \DateTime object
     *
     * @return void
     */
    public function printISO8601Date($date)
    {
        echo $this->dateTimeFromAnything($date)->format('c');
    }

    /**
     * @param mixed $date Anything that we can convert to a \DateTime object
     */
    public function printRFC2822Date($date)
    {
        echo $this->dateTimeFromAnything($date)->format('r');
    }
}

这个类的文档作为一个整体有 @author 标签和 @link 标签。 @author 标签是用来记录这段代码的作者并可以用来重复记录多个作者, @link 标签是用来连接到网站,指示一个网站和代码之间的关系。

在这个类的内部,第一个方法使用了 @param 标记,用于说明传递给该方法的参数类型、名称和描述。此外,它还使用了 @return@throws 标记,用于说明方法的返回类型,以及可能抛出的异常。

第二和第三个方法看起来很相似,与第一个方法同样有个 @param 标记。两个方法的关键差別在于注释区块 使用/省略 @return 标记。@return void 标记明确告诉我们该方法没有返回值。而在过去,省略了 @return void 声明也具有相同效果(沒有返回任何值)。

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/php-the-right-w...

译文地址:https://learnku.com/docs/php-the-right-w...

上一篇 下一篇
贡献者:4
讨论数量: 0
发起讨论 查看所有版本


暂无话题~