我创建了一个函数如下:
//function for first name field
function name ($fname) {
//validate to see if field is empty
if (empty($fname)) {
return (false);
}
$welcome_string = '<p> Welcome ' . $fname . '. We\'re glad you\'re here! Take a look around!</p>';
return $welcome_string;
}//end fname function
当函数通过检查时,我回显函数并获取welcome_string。但是,我需要在函数返回false时显示错误。我无法弄清楚如何做到这一点。下面是我调用函数的代码:
echo name($fname);
答案 0 :(得分:1)
您要做的是添加一个检查:
$result = name($fname);
if ($result) {
echo $result;
} else {
echo "There was an error.";
}
使用三元组if,你可以用速记:
$result = name($fname);
echo $result ? $result : "There was an error.";
甚至更短而不引入新变量:
echo name($fname) ?: "There was an error.";
答案 1 :(得分:0)
你可以这样做:
$result = name($fname);
echo $result?$result:"error message";
答案 2 :(得分:0)
<?php
function greeting($name)
{
if (empty($name))
return false;
$welcome_string = 'Welcome ' . $name . ". We're glad you're here! Take a look around!\n";
return $welcome_string;
}
foreach(['Rita', 'Sue', '', null, 0, '0'] as $name)
echo ($message = greeting($name))
? $message
: "Who are you?\n";
输出:
Welcome Rita. We're glad you're here! Take a look around!
Welcome Sue. We're glad you're here! Take a look around!
Who are you?
Who are you?
Who are you?
Who are you?