gpt4 book ai didi

php - php 中的全局变量没有按预期工作

转载 作者:IT王子 更新时间:2023-10-29 01:23:15 25 4
gpt4 key购买 nike

我在 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 全局,则 $screen 会为 initSession() 方法正确更新。奇怪。

最佳答案

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

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

关于php - php 中的全局变量没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/107693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com