【问题标题】:Passing a String's True/False Boolean Value into a Functions Argument将字符串的 True/False 布尔值传递给函数参数
【发布时间】:2016-03-21 18:37:17
【问题描述】:

如果可以的话,非常感谢您阅读和回复。

  • 在一个函数中,我测试一个条件并创建一个字符串“真”或“假”,然后我创建一个全局变量。
  • 然后我以该字符串为参数调用另一个函数
  • 在该函数的 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 将保持一个“真”值,但事实并非如此。

【问题讨论】:

  • $string 里面真的有值吗?否则 $status 显然会是错误的。另外,我不会使用“true”字符串,我只会使用实际的布尔值。
  • 您可能打算使用另一条评论中概述的if($condition != true),检查 PHP 的 TRUE 常量,而不是字符串文字和 $status = true;,所以很难在这里说出您想要做什么. php.net/manual/en/language.types.boolean.php
  • 我已经留下了这个问题。

标签: php boolean parameter-passing


【解决方案1】:

我认为这里的关键是 PHP 会将空字符串评估为 false 并将非空字符串评估为 true,并且在设置和比较布尔值时确保使用不带引号的常量。使用truefalse 而不是'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';
}

【讨论】:

  • 谢谢迈克尔。我已经更新了我的帖子以试图澄清。我不想将字符串设置为true,而是测试字符串是否为实例化,然后将字符串设置为true,以便稍后进行测试。
  • 太棒了!谢谢!我看到我也没有回应 test_another_condition,所以这没有帮助。
猜你喜欢
  • 2016-08-28
  • 2011-05-12
  • 2011-12-28
  • 2011-04-27
  • 1970-01-01
  • 2015-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多