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

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

问题描述

 函数foo(){
global $ var;
//其余代码
}

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



这是不好的做法吗?

解决方案

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

通常(总是?)您可以在诸如 preg_replace_callback()像这样:

prereg_replace_callback('!pattern!',数组($ obj,'method'),$ str);

请参阅 callbacks for more。



关键是对象已经被绑定到PHP上,并在某些方面导致一些尴尬。



不要过分关注将不同语言的标准或结构应用于PHP。另一个常见的错误是试图通过将对象模型粘贴到所有东西上来将PHP变成纯粹的OOP语言。



与其他任何东西一样,使用全局变量,过程代码,一个特定的框架和面向对象,因为它是有意义的,解决了一个问题,减少了你需要编写的代码数量,或者使它更易于理解,而不是因为你认为你应该。


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

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;.

Is this bad practice?

解决方案

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.

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.

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

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.

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天全站免登陆