PHP中的全局变量无法按预期工作 [英] global variables in php not working as expected

查看:89
本文介绍了PHP中的全局变量无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在php中遇到全局变量的麻烦.我在一个文件中设置了$screen var,它需要另一个文件,该文件调用在另一个文件中定义的initSession(). initSession()声明global $screen,然后使用第一个脚本中设置的值进一步处理$ screen.

I'm having trouble with global variables in php. I have a $screen var set in one file, which requires another file that calls an initSession() defined in yet another file. The initSession() declares global $screen and then processes $screen further down using the value set in the very first script.

这怎么可能?

为了使事情更加混乱,如果您尝试再次设置$ screen然后调用initSession(),它将使用再次使用的值.以下代码将描述该过程.有人可以解释一下吗?

To make things more confusing, if you try to set $screen again then call the initSession(), it uses the value first used once again. The following code will describe the process. Could someone have a go at explaining this?

$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()方法正确更新.奇怪.

Update:
If I declare $screen global again just before requiring the second model, $screen is updated properly for the initSession() method. Strange.

推荐答案

Global不会使变量成为全局变量.我知道这很棘手:-)

Global DOES NOT make the variable global. I know it's tricky :-)

Global表示将使用本地变量,就好像它是具有较大作用域的变量.

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.

Note that global vars are rarely a good idea. You can code 99.99999% of the time without them and your code is much easier to maintain if you don't have fuzzy scopes. Avoid global if you can.

这篇关于PHP中的全局变量无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆