将字符串的True/False布尔值传递给函数参数 [英] Passing a String's True/False Boolean Value into a Functions Argument
问题描述
非常感谢您的阅读和回复.
Thank you so much for reading and responding if you can.
- 在一个函数中,我测试一个条件并创建一个字符串"true"或"false",然后再创建一个全局变量.
- 然后我使用该字符串作为参数调用另一个函数
-
在该函数的if语句中,我要基于'true'或'false'的字符串布尔值进行测试
- 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;
}
}
我的想法是$ condition将具有"true"值,但事实并非如此.
My thinking is that $condition will hold a 'true' value, but this is not so.
推荐答案
我认为这里的关键是PHP会将空字符串评估为false,将非空字符串评估为true,并且在设置和比较布尔值时请确保使用常量而不引号.使用true
或false
而不是'true'
或'false'
.另外,建议您编写if语句,以便它们在单个变量上设置替代值,或者在条件失败时函数返回替代值的情况下.
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';
}
这篇关于将字符串的True/False布尔值传递给函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!