我在php中遇到全局变量问题.我$screen在一个文件中有一个var set,它需要另一个文件来调用另一个文件中initSession()定义的文件.该initSession()声明global $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"
Run Code Online (Sandbox Code Playgroud)
更新:
如果我$screen在要求第二个模型之前再次声明全局,则会为该initSession()方法正确更新$ screen .奇怪.
e-s*_*tis 61
Global不要使变量全局化.我知道这很棘手:-)
Global表示将使用局部变量,就好像它是具有更高范围的变量一样.
EG:
<?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'
?>
Run Code Online (Sandbox Code Playgroud)
请注意,全局变量很少是一个好主意.如果没有模糊范围,您可以在没有它们的情况下编码99.99999%的时间,并且您的代码更容易维护.global如果可以,请避免.
Ath*_*ena 15
global $foo并不意味着"使这个变量全局化,以便每个人都可以使用它".global $foo表示" 在此函数的范围内,使用全局变量$foo".
我假设从你的例子中,每次,你指的是函数内的$ screen.如果是这样,您将需要global $screen在每个功能中使用.
| 归档时间: |
|
| 查看次数: |
71907 次 |
| 最近记录: |