当我想使用在函数外部声明的变量时,是否有最佳实践/建议:
全局 $myVar
$GLOBALS['myVar']
谢谢。
最佳答案
嗯,你应该只在有限的情况下使用全局变量,但要回答你的问题:
global
可能稍微快一些(它很少会产生影响)。$GLOBALS
(不是$GLOBAL
)更具可读性,因为每次看到它,您就知道您正在访问/更改全局变量。这对于避免讨厌的错误至关重要。- 在函数内部,如果你想取消设置一个全局变量,你必须使用
unset($GLOBALS['varname'])
,而不是global $varname;取消设置($变量名);
。
关于第 1 点和第 2 点,我会 quote萨拉戈蒙在这里:
What does that mean for your use of the
$GLOBALS
array? That's right, theglobal
keyword is technically faster. Now, I want to be really clear about one thing here. The minor speed affordance given by using your globals as localized [compiled variables] needs to be seriously weighed against the maintainability of looking at your code in five years and knowing that$foo
came from the global scope.something_using($GLOBALS['foo']);
will ALWAYS be clearer to you down the line thanglobal $foo; /* buncha code */ something_using($foo);
Don't be penny-wise and pound foolish..
关于PHP 全局或 $GLOBALS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3573847/