【问题标题】:How to handle PHP function error?如何处理 PHP 函数错误?
【发布时间】:2009-08-06 20:18:43
【问题描述】:

我如何为 PHP 函数失败形成 if/else 语句?我希望它以一种方式定义$results,如果它有效,另一种方式如果它不起作用。我不想简单地显示错误或在失败时终止错误消息。

目前,我有:

if(file_get_contents("http://www.address.com")){
    $results = "it worked";}
else {
    $results = "it didnt";}
return $results

【问题讨论】:

    标签: php exception-handling conditional-statements


    【解决方案1】:

    你想要 PHP 的 try/catch functions

    它是这样的:

    try {
        // your functions
    }
    catch (Exception e){
        //fail gracefully
    }
    

    【讨论】:

    • 我认为 try/catch 仅适用于 PHP5 并且使用 throw 抛出异常。不过不确定...
    • x3ro 是对的,恐怕 try/catch 仅适用于仅由 PHP 的新 OO 样式功能(如 PDO)引发的异常。所以不是像 file_get_contents() 这样的内置函数,如果文件不存在会引发警告错误。但是,您可以从任何地方抛出异常,我认为可以通过 ErrorException 类将正常的致命错误发送到异常。见php.net/manual/en/language.exceptions.phpphp.net/manual/en/class.errorexception.php
    【解决方案2】:
    if(@file_get_contents("http://www.address.com");){
        $results = "成功了";}
    别的 {
        $results = "它没有";}
    返回$结果
    

    通过在函数前面加上@,您可以隐藏它的错误消息。

    【讨论】:

      【解决方案3】:

      正如 contagious 所说,如果函数抛出异常,try/catch 函数会很好地工作。但是,我认为您正在寻找的是一种处理函数结果的好方法,它返回您的预期结果,如果它抛出异常则不一定。我不认为 file_get_contents 会抛出异常,而只是返回 false。

      您的代码可以正常工作,但我注意到一个额外的 ;在 if 语句的第一行。

      if (file_get_contents("http://www.address.com")) {
          $results = "it worked";
      } else {
          $results = "it didnt";
      }
      return $results;
      

      此外,您可以将函数调用的结果存储到变量中,以便以后使用。

      $result = file_get_contents("http://www.address.com");
      if ($result) {
          // parse your results using $result
      } else {
          // the url content could not be fetched, fail gracefully
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-13
        相关资源
        最近更新 更多