PHP 全局或 $GLOBALS

标签 php variables function global

当我想使用在函数外部声明的变量时,是否有最佳实践/建议:

  1. 全局 $myVar
  2. $GLOBALS['myVar']

谢谢。

最佳答案

嗯,你应该只在有限的情况下使用全局变量,但要回答你的问题:

  1. global 可能稍微快一些(它很少会产生影响)。
  2. $GLOBALS(不是 $GLOBAL)更具可读性,因为每次看到它,您就知道您正在访问/更改全局变量。这对于避免讨厌的错误至关重要。
  3. 在函数内部,如果你想取消设置一个全局变量,你必须使用unset($GLOBALS['varname']),而不是global $varname;取消设置($变量名);

关于第 1 点和第 2 点,我会 quote萨拉戈蒙在这里:

What does that mean for your use of the $GLOBALS array? That's right, the global 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 than global $foo; /* buncha code */ something_using($foo); Don't be penny-wise and pound foolish..

关于PHP 全局或 $GLOBALS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3573847/

相关文章:

php - 如何在 Laravel 中使用 hasOne 关系查询第三个表?

search - 在 vim 中查找变量的下一次出现

javascript - 命名函数在 JavaScript 中被低估了吗?

postgresql - 我正在尝试为 postgresql 编写一个函数来进行一些字符串操作

调用结构类型的函数并返回指针不运行

php - get_terms() orderby 名称不起作用 - wordpress

php - Symfony - 从请求获取一个上传的文件

php - MySQL SELECT 语句只返回一行

c++ - 我可以在两个字符串的字符串格式中使用两个精度 '*' 吗?

css - LESS:如何访问另一个名称中有变量的变量引用的变量?