Php 函数在返回true或false时起作用,但在返回0或1时不起作用 过去($day、$month、$year)中的函数日期2 { $datestring=$year.-“$month.-”$day; 如果(date('Y-m-d',strottime($datestring))

Php 函数在返回true或false时起作用,但在返回0或1时不起作用 过去($day、$month、$year)中的函数日期2 { $datestring=$year.-“$month.-”$day; 如果(date('Y-m-d',strottime($datestring)),php,Php,但是它不会返回任何带有$b=true或$b=false的内容。你知道如何使函数工作吗?将$b赋值给布尔值而不是写入'==1'或'==0'?你可以将变量初始化为布尔值: function date2_in_the_past($day, $month, $year) { $datestring = $year . "-" . $month . "-" . $day; if (date ('Y-m-d', strtotime($datestring)) < date('Y-m-d

但是它不会返回任何带有
$b=true
$b=false的内容。你知道如何使函数工作吗?将
$b
赋值给布尔值而不是写入
'==1'
'==0'

你可以将变量初始化为布尔值:

function date2_in_the_past($day, $month, $year)
{
    $datestring = $year . "-" . $month . "-" . $day;
    if (date ('Y-m-d', strtotime($datestring)) < date('Y-m-d', strtotime("now",time()))) {
        $b = 1;  **// I want $b = true**;
    }
    else { $b = 0; **// I want $b = false;** }

    return $b;
}
//echo date2_in_the_past(24, 10, 2013);     // returns 0
过去($day、$month、$year)中的函数日期2 { $datestring=$year.-“$month.-”$day; 如果(date('Y-m-d',strottime($datestring))
问题出在您评论的回音中。如果要检查变量是否为true或false,应使用

 function date2_in_the_past($day, $month, $year)
    {
     $datestring = $year . "-" . $month . "-" . $day;
     if (date ('Y-m-d', strtotime($datestring)) < date('Y-m-d', strtotime("now",time()))) {
        bool $b = true;  **// I want $b = true**;
    }
    else { bool $b = false; **// I want $b = false;** }

    return $b;
}
而不是

var_dump($variable)
  • 返回true或false并使用运算符===和!==测试返回值
  • 当您在浏览器上回显布尔变量时,您看不到true或false,您将看到1为true,false为nothing打印它将布尔值写入如下字符串:

    $var=false; 如果($var==true) 回声“真”; else if($var==false) 回声“假”


这真的没有道理。当返回布尔值时,您如何测试它返回的内容?您在什么上下文中调用该函数?哦,等等,您正在尝试直接
回显结果
false
没有等效字符串,当
echo
退出时将不显示任何内容
true
在您回显时将显示
1
。不要使用
echo
,而是使用一个正确处理布尔值的条件:
if(date2_in_过去(…){echo'yes…;}
echo $variable;