如果函数validateCustomForm()
什么都不返回,则表示所有变量都已设置。我尝试使用empty()
,但我想,因为函数中有一些东西总是返回false。
如何检查函数是否返回某些内容?
<?php
function validateCustomForm(){
$os0 = "";
$os1 = "5";
$os2 = "6";
$os3 = "5";
if(!empty($os0)){
//do nothing
}else{
$w = "width is missing";
echo $w;
}
if(!empty($os1)){
//do nothing
}else{
$h = "height is missing";
echo $h;
}
if(!empty($os2)){
//do nothing
}else{
$c = "color is missing";
echo $c;
}
if(!empty($os3)){
//do nothing
}else{
$q = "qty is missing";
echo $q;
}
}//end function
$valid = validateCustomForm();
if(!empty($valid)){
echo "something is missing";
} else{
echo "all good";
}
?>
答案 0 :(得分:2)
<?php
function validateCustomForm(){
$os0 = "";
$os1 = "5";
$os2 = "6";
$os3 = "5";
$errors = array();
if(empty($os0)){
$errors[] = "width is missing";
}
if(empty($os1)){
$errors[] = "height is missing";
}
if(empty($os2)){
$errors[] = "color is missing";
}
if(empty($os3)){
$errors[] = "qty is missing";
}
if(!empty($errors)) {
return $errors;
}
return TRUE;
}//end function
$valid = validateCustomForm();
if($valid !== TRUE){
echo "something is missing: ";
echo implode(',' , $valid);
} else{
echo "all good";
}
?>
答案 1 :(得分:0)
你应该返回一些函数而不是echo。如下所示
<?php
function validateCustomForm(){
$os0 = "";
$os1 = "5";
$os2 = "6";
$os3 = "5";
$error = false;
if(!empty($os0)){
//do nothing
}else{
$w = "width is missing";
$error = true;
}
if(!empty($os1)){
//do nothing
}else{
$h = "height is missing";
$error = true;
}
if(!empty($os2)){
//do nothing
}else{
$c = "color is missing";
$error = true;
}
if(!empty($os3)){
//do nothing
}else{
$q = "qty is missing";
$error = true;
}
return $error;
}//end function
$valid = validateCustomForm();
if(!empty($valid)){
echo "something is missing";
} else{
echo "all good";
}
?>