Why is global $object_name discouraged?

2019-07-07 06:21发布

I've got two classes, and currently I reference one from the other by using this:

ClassB::func()
{
    global $classAObject;
    echo $classAObject->whatever();
}

However, I've been told that using global is discouraged. Is it, and why?

标签: php class
2条回答
The star\"
2楼-- · 2019-07-07 07:02

The reason is that it flubs the idea of OOP encapsulation. It's much better to do:

ClassB::func($classAObject)
{
    echo $classAObject->whatever();
}
查看更多
我只想做你的唯一
3楼-- · 2019-07-07 07:03

There are many reasons not to use globals. Here's just a few:

  1. Scope
    • In a large system it can get easy to accidentally reassign global variables if you reuse a semi-common name
    • Variables in Global Scope increase your scripts memory footprint. Not always important, but can be
    • In some other languages, its not necessary to grab your global variables - they are available by default - this can lead to bugs if you forget to declare a same-named variable as local
  2. Coupling
    • In good software design, components should be loosely coupled. Global variables implies tight coupling.
  3. Maintenance
    • A global variable can be changed by any other code, anywhere. Especially in large systems this can make debugging existing code or adding new code a nightmare.

A better way to handle the example you gave in your post would be to pass the object containing the data you need.

classB::func($obj) 
{
   echo $obj->whatever();
}

$obj = new classAObject;
classB::func($obj);
查看更多
登录 后发表回答