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

Php 如何通过函数将当前定义的变量传递到包含的文件中,php,include,Php,Include,我试图使用函数包含一个文件,我定义了几个变量。我想访问包含的文件以访问变量,但因为我使用函数包含它,所以无法访问它。示例场景如下: i、 e索引的内容如下: index.php <? ... function include_a_file($num) { if($num == 34) include "test.php"; else include "another.php" } ... $greeting = "Hello"; include_a_file(3);

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

i、 e索引的内容如下:

index.php

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

测试文件正在抛出一条警告,表示未定义
$greeting

是否确实正确包含?记住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"; 
}

这是行不通的
include
require
就好像您要包含的代码在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);

$greeting
定义为常量,而不是抱歉,这是一个示例场景,我定义了10多个变量。此外,它们也会发生变化。@jayharris将其定义为一个常数,而不仅仅是设置
$greeting=“”?@DarylGill使其成为全局的,在include文件中,您可以在