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

牧云@^-^@ 提交于 2019-12-11 02:16:48

问题


Thank you so much for reading and responding if you can.

  • In one function I test a condition and make a string 'true' or 'false', which then I make a global variable.
  • Then I call another function with that string as the parameter
  • Within that function's if statement, I want to test based off the strings boolean value of 'true' or '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;
         }
    
    }
    

My thinking is that $condition will hold a 'true' value, but this is not so.


回答1:


I think the key here is PHP will evaluate empty strings as false and non-empty strings as true, and when setting and comparing booleans make sure to use constants without quotes. Use true or false not 'true' or 'false'. Also, I suggest writing your if statements so they will set alternate values on a single variable, or in the case of a function return an alternate value when the condition fails.

I made some small modifications to your code so that your function will evaluate true

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


来源:https://stackoverflow.com/questions/34298241/passing-a-strings-true-false-boolean-value-into-a-functions-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!