代码注释

PHPDoc

PHPDoc 是注释 PHP 代码的非官方标准,有多种不同 标签 可供选择,标签和实例的完整列表可以在 PHPDoc manual 的操作手册中找到

下面是一个范例,说明如何对一个带有少量方法的类进行文档化:

  1. <?php
  2. /**
  3. * @author A Name <a.name@example.com>
  4. * @link http://www.phpdoc.org/docs/latest/index.html
  5. */
  6. class DateTimeHelper
  7. {
  8. /**
  9. * @param mixed $anything Anything that we can convert to a \DateTime object
  10. *
  11. * @throws \InvalidArgumentException
  12. *
  13. * @return \DateTime
  14. */
  15. public function ($anything)
  16. {
  17. $type = gettype($anything);
  18. switch ($type) {
  19. // Some code that tries to return a \DateTime object
  20. }
  21. throw new \InvalidArgumentException(
  22. "Failed Converting param of type '{$type}' to DateTime object"
  23. );
  24. }
  25. /**
  26. * @param mixed $date Anything that we can convert to a \DateTime object
  27. *
  28. * @return void
  29. */
  30. public function printISO8601Date($date)
  31. {
  32. echo $this->($date)->format('c');
  33. }
  34. /**
  35. * @param mixed $date Anything that we can convert to a \DateTime object
  36. */
  37. public function printRFC2822Date($date)
  38. {
  39. echo $this->($date)->format('r');
  40. }
  41. }

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

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

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

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

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

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