Jump to content

Global Variables.. Bad Practice?


eldan88
Go to solution Solved by Ch0cu3r,

Recommended Posts

Hey. I have been reading that global variables are bad practice, and should be avoided. What are your thoughts on that?

 

If that is the case, how would I be able to rewrite a simple function authenticate function, where the database object calls the escape value method in my database class. (Note the the database class is already instantiated in the database.php file and is assigned to the $database variable)

 

Thanks for your help!

      public static function authenticate($username="",$password ="") {
          global $database; // How would I use a different method other then global?
          $username = $database->escape_value($username);
          $password = $database->escape_value($password);
          $sql = " SELECT * FROM users ";
          $sql .= " WHERE username = ".  "{$username} ";
          $sql .= " AND password = ". "{$password} ";
          $sql .= " LIMIT 1   ";
          $result_array = self::find_by_sql($sql);
          return !empty($result_array) ? array_shift($result_array) : false;
          
      }
Link to comment
Share on other sites

  • Solution

You'd pass your $database instance to your other objects __constructor and set it as a property. I think this is referred to as dependency injection

 

Not the best example

class classA {
   public function specialMethod() {
       // do somthing
   }
}

class classB {

   private $obj_a;

   public __construct(classA $objA) {
        $this->obj_a = $objA; // save objA as property
   }

   public function someMethod() {
       $this->obj_a->specialMethod(); // call specialMethod() in $objA
   }
}

$objA = new classA();
$objB = new classB($objA); // inject ObjectA into classB
$objB->someMethod();
Edited by Ch0cu3r
Link to comment
Share on other sites

Not all global variables are to be avoided, certain ones are pretty useful and nothing should keep you from using them (like the superglobal arrays $_GET, $_POST, $_SERVER etc. and constants; except if your script requires a certain type and deprecates the other).

Using the global keyword breaks variable encapsulation and is usually a sign of doing it wrong.

Link to comment
Share on other sites

In fact, even the superglobals are a "bad idea", but given PHP's loose structure of "start whichever script you like, where ever you like, how you like", there's not realy any other way of doing it.

 

Anyway, the problem with globals is that they just exist. You never know where they came from or what other pieces of code have done to them before you got to them.

So if your routine needs to parse GET parameters you might be tempted to take $_GET and start modfifying it with a loop, leaving it empty at the end. The next function in your script may also want to do something with $_GET and find it empty. You'll never notice that your second piece of code has stopped working because of something the other code did, because there is nothing in your code that suggests that the processed version of $_GET is sent to the second piece of code.

 

So, think of functions and methods as black-boxes. All the data they need is given to them through the function parameters, they should *never* assume that something exists in the environment around them. That way you have complete control over what data goes where and it becomes much clearer what data is modified by which function.

Link to comment
Share on other sites

Global variables are especially bad in an OO setting where each object is supposed to represent a concrete entity with clearly defined boundaries. 'global' completely bypasses those boundaries, negating one of the fundamental tenets of OO. 'Static' fields and methods do the same, since they're called on a class rather than an object, and can therefore be invoked in any context/scope. There are certain scenarios where 'static' is appropriate, but usually people use it a lot like 'global' - a quick and lazy workaround for bad app design which has its own pitfalls. So, your code example has potentially two strikes against it.

 

You're trying to learn from Lynda.com, right? I never liked her/their tutorials. If you want to learn OOP the right way, get Zandstra's book, then read the Gang of Four's book. Those two resources will get you on the right track.

Link to comment
Share on other sites

Hey Kevin. I have a question on what you just said.  If I create a class called database, and then instantiate that class on the database.php file (where I initially created the class) and then assign it to $database, and lets say i then define the variable $database globally,  how am I breaking the boundaries. Aren't I just calling an object globally? I feel like its different then a static method.

 

I am also not sure what you mean by "where each object is supposed to represent a concrete entity with clearly defined boundaries."

 

 

Yes I am getting these tutorials from Lynda.com. I watch them on my way to work while I commute. I am done with the tutorials anyway, and I looking to expand my repertoire on OOP. Will defiantly start on what you have mentioned.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.