PHP中的全局变量无法按预期工作
我在php中遇到全局变量的麻烦。我在一个文件中设置了一个$ screen
变量,它需要另一个文件调用另一个文件中定义的initSession()
。 " initSession()"声明" global $ screen",然后使用第一个脚本中设置的值进一步处理$ screen。
这怎么可能?
为了使事情更加混乱,如果我们尝试再次设置$ screen然后调用initSession()
,它将使用再次使用的值。以下代码将描述该过程。有人可以解释一下吗?
$screen = "list1.inc"; // From model.php require "controller.php"; // From model.php initSession(); // From controller.php global $screen; // From Include.Session.inc echo $screen; // prints "list1.inc" // From anywhere $screen = "delete1.inc"; // From model2.php require "controller2.php" initSession(); global $screen; echo $screen; // prints "list1.inc"
更新:
如果我在需要第二个模型之前再次声明$ screen全局,则$ screen将为initSession()
方法正确更新。奇怪的。
解决方案
我们需要在引用它的每个函数中放置" global $ screen",而不仅仅是每个文件的顶部。
全局范围跨越包含的文件和必需的文件,除非使用函数中的变量,否则无需使用global关键字。我们可以尝试使用$ GLOBALS数组。
Global
不会使变量成为全局变量。我知道这很棘手:-)
Global表示将使用局部变量,就好像它是具有更大作用域的变量一样。
例如:
<?php $var = "test"; // this is accessible in all the rest of the code, even an included one function foo2() { global $var; echo $var; // this print "test" $var = 'test2'; } global $var; // this is totally useless, unless this file is included inside a class or function function foo() { echo $var; // this print nothing, you are using a local var $var = 'test3'; } foo(); foo2(); echo $var; // this will print 'test2' ?>
注意,全局变量很少是一个好主意。如果没有模糊范围,我们可以在99.99999%的时间中不使用它们而编写代码,并且代码更易于维护。如果可以,请避免使用global
。
global $ foo
并不意味着"使该变量成为全局变量,以便每个人都可以使用它"。 global $ foo
的意思是"在此函数的范围内,使用全局变量$ foo
"。
我假设从示例来看,每次我们都在函数中引用$ screen。如果是这样,我们将需要在每个函数中使用global $ screen
。
如果要在使用许多功能的任务期间访问许多变量,请考虑制作一个"上下文"对象来容纳这些东西:
//We're doing "foo", and we need importantString and relevantObject to do it $fooContext = new StdClass(); //StdClass is an empty class $fooContext->importantString = "a very important string"; $fooContext->relevantObject = new RelevantObject(); doFoo($fooContext);
现在,只需将此对象作为参数传递给所有函数即可。我们将不需要全局变量,并且函数签名保持清晰。以后将空的StdClass替换为实际上具有相关方法的类也很容易。