Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 用于验证的程序流_Php_Validation_Flow - Fatal编程技术网

Php 用于验证的程序流

Php 用于验证的程序流,php,validation,flow,Php,Validation,Flow,编写“验证代码”时,最好的方法是什么?像这样: if(!condition1) { print('error'); return false; } if(!condition2) { print('error'); return false; } do_something(); return true; 或者像这样: if(condition1) { do_something(); if(condition2) { return true; } els

编写“验证代码”时,最好的方法是什么?像这样:

if(!condition1) {
  print('error');
  return false;
}

if(!condition2) {
  print('error');
  return false;
}

do_something();
return true;
或者像这样:

if(condition1) {
  do_something();

  if(condition2) {
    return true;
  } else {
    print('error');
    return false;
} else {
    print('error');
    return false;
}

第一种方法对我来说似乎更清晰,但我不确定使用一种方法比使用另一种方法是否有任何优点。

第二个函数与第一个函数的作用不同,因为它运行
do_something()
,即使条件2为false

无论如何,我更喜欢结合我的条件句,两个例子:

if(!condition1 || !condition2) {
  print('error');
  return false;
} else {
  do_something();
  return true;
}
假设您需要不同的错误消息:

if(!condition1) {
  print('error1');
  return false;
} elseif(!condition2) {
  print('error2');
  return false;
} else {
  do_something();
  return true;
}
我加入了一个
if/elseif
链。这会让你的意图更清晰。

这会更干净

$str="";
if(!$condition1){
  $str .="- Error! condition 1 is required.<br>";
}

if(!$condition2){
  $str .="- Error! condition 2 is required.<br>";
}

if(trim($str)!=""){
 print("Error occurred -<br>".$str);
 return false;
}else{
 return true;
}
$str=”“;
如果(!$1){
$str.=“-错误!条件1是必需的。
”; } 如果(!$2){ $str.=“-错误!条件2是必需的。
”; } 如果(修剪($str)!=“”){ 打印(“发生错误-
”$str); 返回false; }否则{ 返回true; }
希望这有帮助

这可能会更好,但我还是回答了你。