php - 文档错误标签

标签 php documentation phpdoc

<分区>

我在触发错误的类中有一个方法。

/**
 * Get info
 * @return string|FALSE Info
 */
public function getInfo()
{
    if ($this->info) {
        return $this->info;
    }

    trigger_error('Missing info', E_USER_WARNING);
    return FALSE;
}

我不想在这里抛出异常,因为我真的想要/需要这段代码继续运行。在其他地方,我记录了这个错误,并且记录错误超出了此类的范围。

但是我该如何记录呢?作为异常(exception),我会使用:

/**
 * @throws Exception
 */

是否有类似的错误?我真的希望其他开发人员能够轻松了解我的代码中发生了什么。

最佳答案

没有用于错误的 phpdoc 标记。

trigger_error()返回 bool 值,因此您的方法不会返回或抛出任何东西。除非您的错误处理程序阻止,否则执行将恢复,因此使用 @return 或 @throws 会误用它们,并且可能会让阅读您的代码的任何人感到困惑。


我会使用不同的方法。

我会这样做:

/**
 * Has info
 *
 * @return bool Whether info is available
 */
public function hasInfo()
{
    return (bool) $this->info; // or use isset() or whatever you need
}

/**
 * Get info
 *
 * @throws Exception
 * @return string The info string
 */
public function getInfo()
{
    if (! $this->hasInfo()) {
        throw new Exception('Missing info');
    }

    return $this->info;
}

然后从您的其他代码,您可以:

if ($object->hasInfo()) {
    $info = $object->getInfo();
} else {
    // no info!
}

我还会在我的代码库的根目录中捕获异常:

try {
    MyApp::run();
}
catch(Exception $e) {
    // handle error, eg. display fatal error message
}

关于php - 文档错误标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9772667/

相关文章:

php - 使用 jQuery AJAX 发送 ID 数据

php - @Font-Face 在 codeigniter 中不工作

python - 使用 emacs 将 python 文档字符串突出显示为注释

PHP函数注释

php - 表格中的常用字数统计,而不仅仅是一行

php - 是否可以在 PHP 查询中通过 MySQL 表搜索所有列,而无需输入每个列名称?

MATLAB 不显示用户创建的类私有(private)方法和属性的帮助

java - 添加和完善PHP源代码文档的工具

phpDocumentor - 无法打开输入文件 : phpdoc. php

PhpStorm:有没有办法使用内联 PHPDoc 注释在 return 语句上强制执行类型?