php中的全局变量不按预期工作

frebpwbc  于 5个月前  发布在  PHP
关注(0)|答案(7)|浏览(68)

我在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,那么$screen会为initSession()方法正确更新。

7vhp5slm

7vhp5slm1#

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

klsxnrf1

klsxnrf12#

global $foo的意思不是“让这个变量成为全局变量,这样每个人都可以使用它”。global $foo的意思是“* 在这个函数的作用域 * 内,使用全局变量$foo“。
从你的例子中,我假设每次你都是在函数中引用$screen,如果是这样,你需要在每个函数中使用global $screen

vmjh9lq9

vmjh9lq93#

您需要将global $screen放在引用它的每个函数中,而不仅仅是放在每个文件的顶部。

cnjp1d6j

cnjp1d6j4#

如果你在一个使用很多函数的任务中有很多变量需要访问,可以考虑创建一个“context”对象来保存这些东西:

//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替换为实际具有相关方法的类。

kb5ga3dv

kb5ga3dv5#

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

0yycz8jy

0yycz8jy6#

全局作用域包括包含的和必需的文件,你不需要使用global关键字,除非在函数中使用变量。你可以尝试使用$GLOBALS数组代替。

vyu0f0g1

vyu0f0g17#

全局变量意味着你可以在程序的任何部分使用一个变量。所以如果全局变量不包含在函数或类中,那么使用全局变量就没有用了。

相关问题