当函数调用

时间:2015-08-07 18:28:11

标签: php function scope

我有一个简单的Vars.php页面:

<?php
//Vars.php
$WeekOfDateSelected = date('l, m/d/Y', strtotime($MonthYear));
$NextSundayOfDateSelected = date('l, m/d/Y', strtotime('this Sunday', strtotime($WeekOfDateSelected)));

?>

我有另一个包含Vars.php的PHP并构建一个表:

<html>
<?php
//AnalyticsTest.php

include($_SERVER['DOCUMENT_ROOT']."/~/~/~/~/~/Vars.php");

function WeekTable() {

echo "<table id=\"a\">
<tr>
<th style=\"text-align: center;\"><a href=\"#\">< previous week</a></th>
<th colspan=\"4\" style=\"text-align: center;\"><h2>Week of ";
echo $WeekOfDateSelected;
echo " - "; 
echo $NextSundayOfDateSelected; 
echo "</th>
<th style=\"text-align: center;\"><a href=\"#\">next week ></a></th>
</tr>
</table>";

}

?>

</html>

基本上,当我调用WeekTable()时,除了PHP变量$WeekOfDateSelected$NextSundayOfDateSelected之外,一切都输出正确,输出空白。

1 个答案:

答案 0 :(得分:6)

您需要将这些变量作为参数传递给该函数。否则他们是out of scope

function WeekTable($WeekOfDateSelected,$NextSundayOfDateSelected) {
    // ...
}

确保在调用该函数时传递它们:

 WeekTable($WeekOfDateSelected,$NextSundayOfDateSelected);

您也可以使用global关键字,但这是一个糟糕的编程习惯,因此我不会在此处显示。