Php 传递字符串';将真/假布尔值转换为函数参数
非常感谢您的阅读和回复,如果可以的话Php 传递字符串';将真/假布尔值转换为函数参数,php,boolean,parameter-passing,Php,Boolean,Parameter Passing,非常感谢您的阅读和回复,如果可以的话 在一个函数中,我测试一个条件并生成一个字符串'true'或'false',然后生成一个全局变量 然后我调用另一个以该字符串作为参数的函数 在该函数的if语句中,我想基于字符串布尔值'true'或'false'进行测试 $email_form_comments = $_POST['comments']; // pull post data from form if ($email_form_comments) $comments_status = true
- 在一个函数中,我测试一个条件并生成一个字符串'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将保持“真实”值,但事实并非如此 我认为这里的关键是PHP将空字符串计算为false,将非空字符串计算为true,在设置和比较布尔值时,确保使用不带引号的常量。使用
true
或false
而不是'true'
或'false'
。此外,我建议编写if语句,以便它们在单个变量上设置备用值,或者在函数的情况下,在条件失败时返回备用值
我对您的代码做了一些小的修改,以便您的函数将计算为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';
}
$string实际上有值吗?否则$status显然将为false。另外,我不会使用“true”字符串,我只会使用实际的布尔值。您可能想使用另一条注释中概述的
if($condition!=true)
,检查PHP的true常量,而不是字符串文本和$status=true代码>所以很难说你想在这里做什么。我留下了这个问题。谢谢迈克尔。我已经更新了我的帖子,试图澄清。我不想将字符串设置为true,但是测试一个字符串是否是实例化的,然后将字符串设置为true,这样我以后就可以进行测试了。太棒了!非常感谢。我知道我也没有回应另一种情况,所以这没有帮助。