这个答案很晚,但我所做的是设置一个类,该类将布尔值,数组和整数初始值保存为全局范围静态变量。任何常量字符串都是这样定义的。
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
的static
关键字必须存在于其他类$ A,$ b和$ C不会被全局范围的增值经销商。
没有没有外部访问。如果您不喜欢'global'关键字,请考虑在所有作用域中使用'超全局'$ GLOBALS ['a']',或考虑将参数传递给您的函数。 –
如果它是重要的东西,那么甚至可以使用会话变量。 –