非常感谢您的阅读和回复。
- 在一个函数中,我测试一个条件并生成一个字符串"true"或"false",然后生成一个全局变量
- 然后我用这个字符串作为参数调用另一个函数
-
在该函数的if语句中,我想根据字符串测试"true"或"false"的布尔值
$email_form_comments = $_POST['comments']; // pull post data from form if ($email_form_comments) $comments_status = true; // test if $email_form_comments is instantiated. If so, $comments_status is set to true else $error = true; // if not, error set to true. test_another_condition($comments_status); // pass $comments_status value as parameter function test_another_condition($condition) { if($condition != 'true') { // I expect $condition to == 'true'parameter $output = "Your Condition Failed"; return $output; } }
我的想法是$condition将保持一个"true"值,但事实并非如此。
我认为这里的关键是PHP会将空字符串计算为false,将非空字符串评估为true,并且在设置和比较布尔值时,确保使用不带引号的常量。使用true
或false
,而不是'true'
或'false'
。此外,我建议编写if语句,以便它们在单个变量上设置备用值,或者在函数的情况下,当条件失败时返回备用值。
我对你的代码做了一些小的修改,这样你的功能就会评估出真正的
// simulate post content
$_POST['comments'] = 'foo'; // non-empty string will evaluate true
#$_POST['comments'] = ''; // empty string will evaluate false
$email_form_comments = $_POST['comments']; // pull post data from form
if ($email_form_comments) {
$comments_status = true; // test if $email_form_comments is instantiated. If so, $comments_status is set to true
} else {
$comments_status = false; // if not, error set to true.
}
echo test_another_condition($comments_status); // pass $comments_status value as parameter
function test_another_condition($condition)
{
if ($condition !== true) {
return 'Your Condition Failed';
}
return 'Your Condition Passed';
}