问题
This is my try/catch block in PHP:
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?
回答1:
use isset
function to check if the variable is set or not:
if( isset($_GET['id'])){
$api = new api($_GET["id"]);
echo $api -> processRequest();
}
回答2:
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
$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.
回答3:
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.
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
function api($id = 1) {}
So, it "all depends", but try and fail early if you can.
回答4:
Try checking if the $_GET
was set
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);
}
来源:https://stackoverflow.com/questions/18081677/php-notice-undefined-index-although-using-try-catch