沃梦达 / 编程问答 / php问题 / 正文

PHP中的全局变量被认为是不好的做法吗?如果是这样,为什么?

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

本文介绍了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);

查看回调了解更多信息.

关键是对象已经被绑定到 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中的全局变量被认为是不好的做法吗?如果是这样,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:PHP中的全局变量被认为是不好的做法吗?如果是这样,为什么?

基础教程推荐