PHP注意:未定义索引,尽管使用了try\catch

PHP注意:未定义索引,尽管使用了try\catch,php,try-catch,Php,Try Catch,这是我在PHP中的try/catch块: try { $api = new api($_GET["id"]); echo $api -> processRequest(); } catch (Exception $e) { $error = array("error" => $e->getMessage()); echo json_encode($error); } 当$\u GET[“id”]中没有任何内容时,我仍然会收到通知错误。 如何避免

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

try
{
    $api = new api($_GET["id"]);
    echo $api -> processRequest();
} catch (Exception $e) {
    $error = array("error" => $e->getMessage());
    echo json_encode($error);
}
$\u GET[“id”]
中没有任何内容时,我仍然会收到通知错误。
如何避免出现此错误?

使用
isset
功能检查变量是否已设置:

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

尝试检查是否设置了
$\u 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);
}

如果缺少id意味着什么都不应该处理,那么您应该测试是否缺少id,并优雅地管理失败

if(!isset($_GET['id'] || empty($_GET['id']){
// abort early
}
然后继续,你试着接球

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

function api($id = 1) {}
所以,这“完全取决于情况”,但如果可以的话,请尽早尝试失败。

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

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

自PHP7.0以来,有一个更好且被接受的解决方案:使用。使用它,您可以将代码缩短为

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

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

从PHP7开始,我们现在有了


使用
isset($\u-GET['id'])
array\u-key\u-exists($id',$\u-GET)。。这个问题有一百万个重复项..如果(isset($\u GET['id']){$api=new api($\u GET['id']);}PHP通知不例外。@sangaran可能
$api->processRequest()引发异常?
$api->processRequest()确实为家里的孩子丢了很多东西,这确实是肮脏的,你不应该认为这是一个解决方案。这不等同于ASKER正在寻找的行为。注意,如果不设置变量,则<代码> EMPTY()/<代码>不会触发通知。因此,
isset()
是不必要的。
try
{
    $api = new \Api($_GET['id'] ?? null);
}
catch (\Exception $e)
{
    $error = ["error" => $e->getMessage()];
    return json_encode($error);
}