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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18081677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:57:38  来源:igfitidea点击:

PHP Notice: Undefined index although using try\catch

phptry-catch

提问by Asaf Nevo

This is my try/catch block in PHP:

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

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

When there is nothing in the $_GET["id"], I still get the notice error. How can I avoid getting this error?

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

回答by Nil'z

use issetfunction to check if the variable is set or not:

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

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

回答by Markus Madeja

If you want a fast and "dirty" solution, you can use

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

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

Edit:

编辑:

Since PHP 7.0 there is a much better and accepted solution: using the null coalescing operator (??). With it you can shorten your code to

从 PHP 7.0 开始,有一个更好且被接受的解决方案:使用空合并运算符 (??)。有了它,您可以将代码缩短为

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

and you don't get a notice because you defined what should happen in the case the variable is not defined.

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

回答by Cups

If the absence of id means nothing should then be processed, then you should be testing for the absence of the id, and managing the failure gracefully.

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

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

THEN go on and do you try/catch.

然后继续尝试/捕捉。

Unless of course you were to add some smartness to api() so that is responded with a default id, that you'd declare in the function

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

function api($id = 1) {}

So, it "all depends", but try and fail early if you can.

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

回答by Conrad Lotz

Try checking if the $_GETwas set

尝试检查是否$_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);
}