3

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?

Bojangles
  • 99,427
  • 50
  • 170
  • 208
  • http://softwareengineeringexplored.blogspot.com/2009/06/introduction-global-variables-are-those.html – Erik May 02 '11 at 16:33
  • possible duplicate of [\[PHP\] global in functions](http://stackoverflow.com/questions/5166087/php-global-in-functions) – Gordon May 02 '11 at 17:17
  • Thanks @Gordon - I'll have a read of that thread, as well as @Erik's link - they both look like good resources :-) – Bojangles May 03 '11 at 13:03
  • Possible duplicate of [Are global variables in PHP considered bad practice? If so, why?](http://stackoverflow.com/q/1557787/1255289) – miken32 Mar 11 '17 at 18:09

2 Answers2

7

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);
Erik
  • 20,526
  • 8
  • 45
  • 76
  • Thank you for your better solution and the points above - very helpful answer! I'd upvote this like 5 times but I can't ;-) – Bojangles May 03 '11 at 13:01
0

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

ClassB::func($classAObject)
{
    echo $classAObject->whatever();
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Naftali
  • 144,921
  • 39
  • 244
  • 303