PHP 中的全局变量是否被认为是不好的做法?如果是这样,为什么? [英] Are global variables in PHP considered bad practice? If so, why?

查看:36
本文介绍了PHP 中的全局变量是否被认为是不好的做法?如果是这样,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function foo () {
    global $var;
    // rest of code
}

在我的小型 PHP 项目中,我通常采用程序化的方式.我通常有一个包含系统配置的变量,当我需要在函数中访问这个变量时,我会执行 global $var;.

In my small PHP projects I usually go the procedural way. I generally have a variable that contains the system configuration, and when I nead to access this variable in a function, I do global $var;.

这是不好的做法吗?

推荐答案

当人们在其他语言中谈论全局变量时,其含义与在 PHP 中的含义有所不同.那是因为变量在 PHP 中不是真正全局的.一个典型的 PHP 程序的范围是一个 HTTP 请求.会话变量实际上比 PHP 的全局"变量具有更广泛的范围,因为它们通常包含许多 HTTP 请求.

When people talk about global variables in other languages it means something different to what it does in PHP. That's because variables aren't really global in PHP. The scope of a typical PHP program is one HTTP request. Session variables actually have a wider scope than PHP "global" variables because they typically encompass many HTTP requests.

通常(总是?)您可以像这样在 preg_replace_callback() 之类的方法中调用成员函数:

Often (always?) you can call member functions in methods like preg_replace_callback() like this:

preg_replace_callback('!pattern!', array($obj, 'method'), $str);

有关更多信息,请参阅回调.

See callbacks for more.

重点是对象已经被固定在 PHP 上,并且在某些方面会导致一些尴尬.

The point is that objects have been bolted onto PHP and in some ways lead to some awkwardness.

不要过分担心将来自不同语言的标准或构造应用于 PHP.另一个常见的陷阱是试图通过将对象模型置于一切之上来将 PHP 转变为纯 OOP 语言.

Don't concern yourself overly with applying standards or constructs from different languages to PHP. Another common pitfall is trying to turn PHP into a pure OOP language by sticking object models on top of everything.

像其他任何事情一样,使用全局"变量、过程代码、特定框架和 OOP,因为它有意义、解决问题、减少您需要编写的代码量或使其更易于维护和更易于理解,而不是因为你认为你应该.

Like anything else, use "global" variables, procedural code, a particular framework and OOP because it makes sense, solves a problem, reduces the amount of code you need to write or makes it more maintainable and easier to understand, not because you think you should.

这篇关于PHP 中的全局变量是否被认为是不好的做法?如果是这样,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆