如何通过函数将当前定义的变量传递到包含的文件中

时间:2013-06-27 14:18:13

标签: php include

我正在尝试使用函数包含文件,并且我定义了几个变量。我想访问包含的文件来访问变量,但因为我使用函数包含它,所以无法访问它。示例场景如下:

即索引的内容如下

index.php

<?
...
function include_a_file($num)
{
  if($num == 34)
    include "test.php";
  else
    include "another.php"
}
...
$greeting = "Hello";
include_a_file(3);
...
?>

test.php的内容如下

test.php

<?
echo $greeting;
?>

测试文件发出警告,说明$greeting未定义。

2 个答案:

答案 0 :(得分:2)

这不起作用。 includerequire就好像您所包含的代码实际上是include / require执行时文件的一部分。因此,您的外部文件将在include_a_file()函数的范围内,这意味着$greeting在该函数中是超出范围的。

您必须将其作为参数传递,或者在函数中使其全局:

function include_a_file($num, $var) {
                              ^^^^-option #1
   global $greeting; // option #2
}

$greeting = 'hello';
include_a_file(3, $greeting);

答案 1 :(得分:0)

你确定你的正确包括吗?请记住PHP区分大小写:

$Test = "String"; 
$TEst = "String"; 

两个完全不同的变量..

此外,不要只是回显变量,将其包含在isset条件中:

if (isset($greeting)){
 echo $greeting;
} // Will only echo if the variable has been properly set.. 

或者您可以使用:

if (isset($greeting)){
  echo $greeting;
}else{
  echo "Default Greeting"; 
}