ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.

Advertisements

Using globals in PHP

(Page 2 out of 4)

Using function arguments

One way to stop using the global keyword is to simply pass the values as a function argument, like this:


$var = 'Hello World';

test ($var);

function test($var) {
        echo $var;
}

?>

If you only need to pass one global variable, this is an excellent solution, and should be the standard thing. But what if you have to pass multiple values?

For example, let's imagine we are using a database object, a settings object and a user object. These three objects are used by all the components in our script, and therefore must be passed to each component. If we were to use function arguments, we'd have to do something like this:


$db = new DBConnection;
$settings = new Settings_XML;
$user = new User;

test($db, $settings, $user);

function test(&$db, &$settings, &$user) {
        // Do something
}

?>

Obviously this isn't really working, and as soon as we have another object we will have to add another function argument. We're going to have to do it in a different way.

Using Singletons

One way to solve the problem with function arguments is to use Singletons instead of function arguments. Singletons are a special kind of object which can only be instantiated once, and include a static function to return the object instance. The below example demonstrates a simple Singleton:

// Get instance of DBConnection
$db =& DBConnection::getInstance();

// Set user property on object
$db->user = 'sa';

// Set second variable (which points to the same instance)
$second =& DBConnection::getInstance();

// Should print 'sa'
echo $second->user;

Class DBConnection {
        var $user;
       
        function &getInstance() {
                static $me;

                if (is_object($me) == true) {
                        return $me;
                }

                $me = new DBConnection;
                return $me;
        }

        function connect() {
                // TODO
        }

        function query() {
                // TODO
        }

}

?>

The most important part of the example above is the getInstance() function. This function makes sure that there is only one instance of the DBConnection class, by using a static variable called $me, and returns the instance of the class.

The advantage of using a Singleton is that we don't have to explicitly pass the object, but instead can simple use the getInstance() function to get the object, like this:

function test() {
        $db = DBConnection::getInstance();

        // Do something with the object

}

?>

But there are several disadvantages to using Singletons like this. For one, what if we need multiple objects of a particular class? Since we are using singletons that isn't possible (hence the name singletons). Another problem is that singletons aren't testable with unit tests. It's completely impossible, unless you introduce all kinds of hacks, which is something you obviously don't want. That's why singletons aren't really the magical solution we're looking for either.

« Previous: Introduction & The Global Keyword
Next: The Registry Pattern »



7 Responses to “Using globals in PHP”

  1. Casa's little Blog Says:

    Using globals in PHP

    The headline could misslead you
    PHPit.net published an article how to use GLOBALs, how to use singeltons and the registry pattern in PHP.
    Nice to read and includes some hints for people having trouble understanding or who wants to know what those bu…

  2. PHPDeveloper.org Says:

    PHPit.net: Using globals in PHP

  3. Project D.O Says:

    Why not just use Constants instead? There also various ways to register certain globals and constants to, I use:

    $GLOBALS[”constants”][] array(”function” => “”, “file” => “”, “line” => “”, “name” => “”);

    I can iterate over this array and find out where I place what, when, where and why, plus I could extend the array with anything I want, even if I want, wrap it in a function:

    function register_constant($array_constant) {

    }

    I’m using techniques such as this and others on my site and in its various applications.

  4. Gurudutt Verma Says:

    Hi
    I am kind of new to php and I liked this technique, but still insted of using Class Registry Why don’t you use simple array here and that will saveral function call, and that may improve the prformance,

    I mean to say we are using globals because in most cases we want to improve speed of the system and if we again create several classes and function then it may slow down the system.

    Please correct me if I am wrong. I want to learn php

  5. DevBeta: Shawn Sandy on design, development and technology » Blog Archive » PHPit - Totally PHP » Using globals in PHP Says:

    […] PHPit - Totally PHP » Using globals in PHP In this article you will be shown how to properly use globals in PHP. We will take a look at the global keyword, function arguments, Singletons and the Registry pattern. […]

  6. Spavkov Says:

    This article is very good.
    It points out some nice solutions…

    i hate using globals, and now i got the idea how to avoid it…

    thanks to the author…

  7. Eric Lin Says:

    Very nice tutorial, I have been looking ways to improve my coding, and I will use this technique on my website.

Leave a Reply

About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.
Article Index
  1. Introduction & The Global Keyword
  2. Function Arguments & Singletons
  3. The Registry Pattern
  4. A Request Wrapper & Conclusion
Bookmark Article
Download Article
PDF
Download this article as a PDF file