如何识别它是错误代码还是仅仅是int?

时间:2015-08-09 16:08:47

标签: php

我了解到我可以像这样定义我的错误代码:

class Hello
{
    /** My own error codes */
    const OK    = 0;
    const ERROR = 1;
    const OTHER = 2;

    function Test()
    {
        /** Return the error code if an error was occurred */
        if(an_error_occurred)
            return self::ERROR;

        /** Simulate some simple result. */
        return rand(0, 10);
    }
}

但我对此有些麻烦:

if($Hello->Test() == Hello::ERROR)
    exit('Something happened.');

即使没有发生错误,它仍然会退出,但$ Hello-> Test()给出的值等于1,

我该如何解决这个问题?

或者有更好的方法来定义我自己的错误代码?

1 个答案:

答案 0 :(得分:4)

您不应该为返回值混合含义。正如其他人所提到的,例外就是为此而做的。

class Hello
{
    function Test()
    {
        /** Return the error code if an error was occurred */
        if (an_error_occurred)
            throw new Exception("An error occurred.");

        /** Simulate some simple result. */
        return rand(0, 10);
    }
}

调用它时,你会这样做:

try {
   $foo = $hello->Test();
} 
catch(Exception $e) {
   echo "There was a problem: " . $e->getMessage();
}

只有在 Test 方法中抛出异常时,catch块内的代码才会执行​​。您可以创建自己的异常类型,以便针对不同类型的错误进一步自定义。

检查出来:http://php.net/manual/en/language.exceptions.php