将字符串的 True/False 布尔值传递给函数参数

Passing a String's True/False Boolean Value into a Functions Argument

非常感谢您的阅读和回复。

我的想法是 $condition 将持有 'true' 值,但事实并非如此。

我认为这里的关键是 PHP 会将空字符串评估为 false,将非空字符串评估为 true,并且在设置和比较布尔值时确保使用不带引号的常量。使用 truefalse 而不是 'true''false'。此外,我建议编写您的 if 语句,以便它们将在单个变量上设置备用值,或者在函数的情况下 return 条件失败时的备用值。

我对您的代码做了一些小修改,以便您的函数计算结果为真

// 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';
}