我正在使用全局修饰符的基本 php 示例,它对我不起作用:-|
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo "***: ".$b;
结果如下... $ ***: 2
php.ini 上是否有任何可能影响此的参数?
我也遇到了你的问题。当我使用框架 (Yii) 时,我并没有完全意识到我的代码确实嵌套在函数内部,因此global
没有按预期运行(正如 omadmedia 和其他人所解释的那样)。
我的解决方案非常简单:
global $a;
global $b;
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo "***: ".$b;
信不信由你,我也得到了答案:2。这意味着确实存在一些全局无法正常工作的情况。
尝试找到原因:似乎如果您有一个函数并将 OP 的代码(这是一个 php.net 示例)放入该函数中,您将得到答案 2。这有点奇怪,并且在某种程度上是有道理的。 ..
(我在 Win XP 的 Apache 2.2.8 下使用 PHP 5.2.5)
LE:我的解决方案好的,解决了这个问题:当你在第二个函数中使用 global 时,你显然会得到超全局变量,每个人都可以使用这些变量(即在任何函数之外声明),但是因为 $a 和 $b 在第一个函数中声明,它们不属于该范围,并且不适用于第二个功能。我对解决方案的猜测是在第二个函数之外,也就是在第一个函数内部声明 $a 和 $b 全局。!!请注意,由于各种原因,第一个可能并不那么明显,例如您的文件(仅包含第二个函数)被包含在不同文件中不同函数主体的某处。
As @AgelessEssence answered, global keyword doesn't work if you have a nested function. It is obvious in his example. However, if it is not clear if a file is included. Here is the example.
//a.php
function f() {
require_once('./a_inc.php');
}
f();
//a_inc.php
$a = 12;
function g() {
global $a;
var_dump($a);
}
g();
//result
null
In the code above, $a looks like a global variable. Actually, it is not because it is included in the function f() in a.php and $a is part of function f().
So, when your global keyword doesn't work, check whether it is included in a function. As the solution for this problem well explained in other answers, so I didn't add it here.
您上面的示例代码对我有用。但您也可以使用$GLOBALS超变量。
function Sum()
{
$a = $GLOBALS["a"];
$b =& $GLOBALS["b"];
$b = $a + $b;
}
如果您可以提供帮助,则不应使用全局变量。有更好的方法来制作你的函数。使用参数(参数)(可能通过 引用传递)并返回一个值。
/**
* Calculate the sum of the parameters
* @param int|float $a one or more parameter
* @param int|float $a, ...
* @return int|float
*/
function sum($a)
{
$args = func_get_args();
return array_sum($args);
}
$a = 1;
$b = 2;
$b = sum($a, $b);
我和你有同样的问题,终于找到了答案
工作代码/ DEMO
$a=1;
function showA() {
global $a;
var_export($a);
}
showA(); // outputs "1"
非工作代码/演示
function encapsulation() {
$a=1;
function showA() {
global $a;
var_export($a);
};
showA();
}
encapsulation(); // outputs "NULL"
如您所见,在嵌套函数定义中使用global 关键字时会出现问题
我唯一能想象到的错误是,如果您在首先调用函数后在全局范围内分配变量。也就是说,您的函数实际上是在声明变量,然后您只需在其他地方覆盖它们。例如,调用Sum()
然后执行, 。$a=1
$b=2