PHP 全局或 $GLOBALS [英] PHP global or $GLOBALS
本文介绍了PHP 全局或 $GLOBALS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我想使用在函数外部声明的变量时,是否有最佳实践/建议:
Is there a best practice / recommendation when I want to use a variable declared outside of a function when it comes to using:
全局 $myVar
$GLOBALS['myVar']
谢谢.
推荐答案
你真正应该做的是将变量传递给函数,而不是使用全局变量.
What you should really do is pass the variable to the function instead of using a global at all.
如何通过将变量作为引用参数传递来更改函数外部的变量的示例:
An example how to change a variable outside of the function via passing it as reference parameter:
function myFunc(&$myVar)
{
$myVar = 10;
}
$foo = 0;
myFunc($foo);
var_dump($foo); // yields 10
这篇关于PHP 全局或 $GLOBALS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文