It's not at all important to get it right the first time. It's vitally important to get it right the last time.
Andrew Hunt and David Thomas

Say No to “global”

May 12th, 2011 PHP Tags: , , , , ,

In PHP, a function (or class method) could use variables that reside in the global scope by explicitly stating them with global keyword. For example:

$string = 'an apple above the head';

function break_string() {
  global $string;
  return 'break ' . $string;
}

This practice has some disadvantages, one of them is we can’t directly know the origin of the global variables. Let’s say we have this code:

include 'common_function.php';
include 'pedicure_function.php';
include 'medicure_function.php';

function break_string() {
  global $string;
  return 'break ' . $string;
}

Can you know where is the origin of global $string? We need to look through each of those included files and search for variable $string which resides in global scope. This might take some times, so I propose a better way to utilize global variables.

Let’s create one class as a container to all global variables by using static properties. To illustrate, see this piece of code:

// Global container
class G {
  public static $string;
}

G::$string = 'an apple above the head';

function break_string() {
  return 'break ' . G::$string;
}

Not only that we don’t need to write “global” in every functions, we could also find the origin of global $string easier, because it has G:: prefix. Finding the definition of a class is so much easier than finding a variable because people usually write one class per one file. Let’s take a look at this piece of code:

include 'class/G.php';
include 'common_function.php';
include 'header.inc';

function break_string() {
  return 'break ' . G::$string;
}

In a glance, we could guess that G::$string originated from ‘class/G.php’ because we know for sure that G:: means static properties of class G and usually class G (or Whatever) will be written in file G.php (or Whatever.php).

0saves
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

No Responses to “Say No to “global””

No comments yet


Leave a Reply







XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>