我在php中遇到全局变量问题。我在一个文件中设置了 $ screen var,这需要另一个调用另一个文件中定义的 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 global,则会为 initSession()方法正确更新$ screen。奇怪。

有帮助吗?

解决方案

全局不要使变量成为全局变量。我知道这很棘手: - )

全局表示局部变量将被用作,就好像它是一个具有更高范围的变量

E.G:

<?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 &quot;。

我假设你的例子中每次都是指函数中的$ screen。如果是这样,您将需要在每个函数中使用 global $ 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也很容易。

全局范围跨越包含和必需文件,除非在函数内使用变量,否则不需要使用global关键字。您可以尝试使用$ GLOBALS数组。

在为其定义值之前,必须将变量声明为全局变量。

在函数或类中它是无用的。全局意味着您可以在程序的任何部分使用变量。因此,如果全局未包含在函数或类中,则不使用全局

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top