为什么是全局$ object_name不鼓励? [英] Why is global $object_name discouraged?
本文介绍了为什么是全局$ object_name不鼓励?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个类,目前我使用这个来引用另一个:
I've got two classes, and currently I reference one from the other by using this:
ClassB::func()
{
global $classAObject;
echo $classAObject->whatever();
}
$ b <不鼓励。是吗?为什么?
However, I've been told that using global
is discouraged. Is it, and why?
感谢,
James
推荐答案
有很多原因不使用全局变量。以下是几个例子:
There are many reasons not to use globals. Here's just a few:
- 范围
- 在大型系统中,如果您重复使用半常用名称,则会意外重新分配全局变量
- Global Scope中的变量会增加脚本内存占用。不一定重要,但可以
- 在其他一些语言中,它不需要抓取您的全局变量 - 它们在默认情况下可用 - 如果您忘记声明它们可能会导致错误-named variable as local
- 松耦合。全局变量意味着紧密耦合。
- 通过任何其他代码,任何地方。
classB::func($obj)
{
echo $obj->whatever();
}
$obj = new classAObject;
classB::func($obj);
这篇关于为什么是全局$ object_name不鼓励?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文