为什么我的变量未定义?

时间:2016-07-28 18:14:15

标签: php if-statement math var strtotime

就我使用PHP的有限知识和能力而言,以下代码应该有效:

<?php
////DISPLAY DATE OF NEXT COUNCIL MEETING////

$now = date('U'); //get current time
$firstTues = strtotime("-1 month first Tuesday 4pm"); //get first Tuesday of the month
$secondTues = strtotime("-1 month second Tuesday 5pm"); //get second Tuesday of the month
$fourthTues = strtotime("-1 month fourth Tuesday 5pm"); //get forth Tuesday of the month
$nextTues = strtotime("first Tuesday 4pm"); //get first Tuesday of next month

function nextCouncilMeeting() {

//If todays date less than 1st Tuesday at 11pm, display date for 1st Tuesday 4pm.
if ($now < $firstTues) {
    echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A', $firstTues);
}

//If todays date greater than 1st Tuesday 5pm and less than 2nd Tuesday 11pm, display date for 2nd Tuesday 5pm
elseif ($now > $firstTues and $now < $secondTues) {
    echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A', $secondTues);
}

//If todays date greater than 2nd Tuesday 5pm and less that 4th Tuesday 11pm, display date for 4th Tuesday 5pm
elseif ($now > $secondTues and $now < $fourthTues) {
    echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A', $fourthTues);
} 

//If todays date greater than 4th Tuesday
elseif ($now > $fourthTues){
    echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A', $nextTues);
}
else{
    echo "foobar";
}
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="test">
Current Time: <?php echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A',$now); echo " " . $now;?></br>
First Tuesday: <?php echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A',$firstTues);echo " " . $firstTues;?></br>
Second Tuesday: <?php echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A',$secondTues);echo " " . $secondTues;?></br>
Fourth Tuesday: <?php echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A',$fourthTues);echo " " . $fourthTues;?></br>
Next Month First Tuesday: <?php echo date('F j\<\s\u\p\>S\</\s\u\p\> \a\t g:i A',$nextTues);echo " " . $nextTues;?>
</p>
<h2>Next Council Meeting:</h2>
<h1><?php nextCouncilMeeting()?></h1>
</body>
</html>

但是我的变量抛出错误是未定义的,我做错了什么?

1 个答案:

答案 0 :(得分:1)

如果您运行带有错误报告的程序并设置为显示所有错误,则问题会变得更加清晰。请参阅this demo及其引发的错误。问题是范围界定。 PHP具有功能范围,意味着在函数内部定义的变量在函数内不可见。你应该将你的值作为参数传递给函数,或者走错路线并在函数中将它们声明为全局。