您需要使用global 关键字。以下是有关变量作用域的注意事项:
- 在类或函数中声明的变量会自动作用于该类或函数。
- 默认情况下,在任何类或函数之外声明的变量都是全局的。
- 如果你想在函数中使用全局变量,你必须使用 global 关键字,以便 PHP 知道你的意思是使用全局变量,而不是一些类似命名的局部变量。
这是一个示例,仅使用 $var1。其他变量将使用相同的技术。
b.php
$var1 = "blah";
一个.php
// including b.php causes the global $var1 to be defined
include "b.php";
// outside of any class or function, $var1 refers to the global
echo ($var1 . "\n"); // prints "blah"
function x() {
$var1; // This is a local variable, not the global one.
// within this function, $var1 has not been defined, so you get a blank
// (or perhaps a Notice depending on your log settings) when you try
// to print it out.
echo ($var1."\n");
}
function y() {
// This is how you tell PHP you wish to use a global variable from
// inside a function.
global $var1;
echo ($var1."\n");
}
x();
y();