【问题标题】:PHP Notice: Undefined index although using try\catchPHP 注意:未定义的索引虽然使用 try\catch
【发布时间】:2013-08-06 13:30:26
【问题描述】:

这是我在 PHP 中的 try/catch 块:

try
{
    $api = new api($_GET["id"]);
    echo $api -> processRequest();
} catch (Exception $e) {
    $error = array("error" => $e->getMessage());
    echo json_encode($error);
}

$_GET["id"] 中没有任何内容时,我仍然收到通知错误。 如何避免出现此错误?

【问题讨论】:

  • 使用isset($_GET['id'])array_key_exists('id', $_GET); .. 一百万个重复来计算这个问题..
  • if (isset($_GET['id'])){ $api = new api($_GET['id']); }
  • PHP 通知不是例外。
  • @dbf 也许可以。但是访问未定义的数组索引仍然会引发 NOTICE。如果 OP 想要避免它,他应该设置一个适当的错误处理程序,将通知“转换”为异常,或者他可以在 !isset($_GET['id']) 时手动抛出异常
  • $api->processRequest(); 确实会引发异常

标签: php try-catch


【解决方案1】:

使用isset函数检查变量是否设置:

if( isset($_GET['id'])){
    $api = new api($_GET["id"]);
    echo $api -> processRequest();
}

【讨论】:

    【解决方案2】:

    如果你想要一个快速而“肮脏”的解决方案,你可以使用

    $api = new api(@$_GET["id"]);
    

    编辑:

    自 PHP 7.0 以来,有一个更好且被接受的解决方案:使用null coalescing operator (??)。有了它,您可以将代码缩短为

    $api = new api($_GET["id"] ?? null);
    

    并且您没有收到通知,因为您定义了在未定义变量的情况下应该发生的情况。

    【讨论】:

    • 对于家里的孩子来说,这确实是,你不应该认为这是一个解决方案。
    • 这不等同于提问者正在寻找的行为。
    【解决方案3】:

    如果没有 id 意味着什么都不应该被处理,那么你应该测试是否没有 id,并优雅地管理失败。

    if(!isset($_GET['id'] || empty($_GET['id']){
    // abort early
    }
    

    然后继续尝试/抓住。

    当然,除非您要为 api() 添加一些智能,以便以默认 id 响应,您将在函数中声明

    function api($id = 1) {}
    

    所以,这“一切都取决于”,但如果可以,请尽早尝试并失败。

    【讨论】:

    • 请注意,如果未设置变量,empty() 不会触发通知。因此,isset() 是不必要的。
    【解决方案4】:

    你必须捕捉 Throwable 而不是 Exception:

    } catch (Throwable $e) {
    

    【讨论】:

      【解决方案5】:

      尝试检查是否设置了$_GET

      try
      {
          if(isset($_GET["id"]))
          {
            $api = new api($_GET["id"]);
            echo $api -> processRequest();
          }
      } catch (Exception $e) {
          $error = array("error" => $e->getMessage());
          echo json_encode($error);
      }
      

      【讨论】:

        【解决方案6】:

        从 PHP 7 开始,我们现在有了 Null Coalescing Operator

        try
        {
            $api = new \Api($_GET['id'] ?? null);
        }
        catch (\Exception $e)
        {
            $error = ["error" => $e->getMessage()];
            return json_encode($error);
        }
        

        【讨论】:

          【解决方案7】:

          try...catch 的结构

           <?php
          
          try {
              // perform some task
          } catch (Exception $ex) {
              // jump to this part
              // if an exception occurred
          }
          

          你可以使用isset

               <?php
              if(isset($_GET['id'])){
                   $api = new api($_GET["id"]);
                   echo $api -> processRequest();
               }else{
                    $error = array("error" => $e->getMessage());
                    echo json_encode($error);
               }
              ?>
          

          奖金 示例:

          <?php
          if(isset($_GET['name'])){
                $name = $_GET['name']; 
           }else{
                $name = "Name not set in GET Method";
           }
          if(isset($_GET['age'])){
                $name = $_GET['age']; 
           }else{
                $name = "<br>Age not set in GET Method";
           }
          echo $name;
          echo $age;
          ?>
          

          【讨论】:

          • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-03-07
          相关资源
          最近更新 更多