简体   繁体   English

PHP 在 function() 中使用 exit() 一次只返回 1 个值

[英]PHP using exit() inside a function() to return only 1 value at a time

Suppose I have written the following function to check empty posted values:假设我编写了以下 function 来检查空的发布值:

function checkEmpty($postValue, $msg){
  if($postValue == null){
    return alert_danger($msg);
    exit(); // NOT WORKING AS EXPECTED
  }
}

And I am trying to call it for several input values this way:我试图以这种方式为几个输入值调用它:

echo checkEmpty($city, "City cannot be empty");
echo checkEmpty($phone, "phone cannot be empty");
echo checkEmpty($name, "name cannot be empty");

Now when I call this function above it echoes all the three values as it should be but I do not want that.现在,当我在上面调用这个 function 时,它会呼应所有三个值,但我不希望这样。 I want it to return 1 error at a time.我希望它一次返回 1 个错误。 If city is empty it should return City cannot be empty only and not the others.如果city是空的,它应该返回City cannot be empty的,而不能是其他的。 When the user has corrected the error it should then proceed to check the next error.当用户纠正了错误后,它应该继续检查下一个错误。 But it seems that the exit() used inside the function is not working as expected.但似乎 function 内部使用的exit()没有按预期工作。 I could use the following method:我可以使用以下方法:

if($name == null){
  echo alert_danger("Please enter your Name.");
  exit();
}

if($email == null){
  echo alert_danger("Please enter your Email ID.");
  exit();
}

if($phone == null){
  echo alert_danger("Please enter your Phone number.");
  exit();
}

But that makes the code too big unnecessarily if I have 15-20 variables to be checked.但是,如果我要检查 15-20 个变量,这会使代码不必要地过大。 That's why I wanted to use the function method here as tried earlier.这就是为什么我想在这里使用之前尝试过的 function 方法。 What should be the solution?解决方案应该是什么?

Use a function that echoes the error then dies after:使用 function 回显错误,然后在以下情况下消失:

function checkEmpty($postValue, $msg){
    if($postValue == null){
        echo alert_danger($msg);
        exit();
    }
}

checkEmpty($city, "City cannot be empty"); //without echo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM