ONLamp.com    
 Published on ONLamp.com (http://www.onlamp.com/)
 See this if you're having trouble printing code examples


PHP Foundations Advanced PHP References

by John Coggeshall
09/12/2002

Welcome back! In my last column I introduced you to basic PHP references and how they are used. This week, I'll take that basic introduction a step further and implement some of the more advanced uses for references in PHP. First, I'll be discussing the concept of returning a reference from a function, followed by using references within objects. Let's get started.

Returning by Reference

Last week, I discussed how references could be used as parameters of functions in order to return multiple values. This week, I'll look at ways to use references as the actual return value of the function and how this can be useful to developers. To assist us in our discussion, consider the following classes:

<?php
    class A {
        function printmsg() {
            echo  "Class is A<br>";
        }
    }
    class B {
        function printmsg() {
            echo "Class is B<br>";
        }
    }
$toolbox[] = new A();
$toolbox[] = new B();
?>

As you can see, we have created two very simple classes, A and B, each of which contains a single member function called printmsg(). Then, an instance of each class is created and stored in the array $toolbox. With this overhead out of the way, let's discuss the passing by reference function. Although there are many uses for a return by reference function, the specific function that I will be creating today will accept a single parameter (for a simple case like this, a boolean value) and return a reference to one of the above created objects, as shown.

<?php
    function &selectObject($which = false) {
        global $toolbox;
        if($which == true) 
            return $toolbox[0];
        return $toolbox[1];
    }
    $tool =& selectObject(true);
    $tool->printmsg();
    $anothertool =& selectObject(false);
    $anothertool->printmsg();
?>

So what exactly does this selectObject() function we've created do? Looking at the function declaration, we see that it takes a single boolean parameter $which, but what is the ampersand (&) character in front of the function name for? This symbol defines our function as one that returns a PHP reference instead of a complete variable. Looking at the code within the function, we can see that the function returns one of the objects stored in the $toolbox array defined previously. Hence, depending on the value of our parameter, we return a reference to one of the objects we've defined.

Related Reading

PHP Cookbook
By David Sklar, Adam Trachtenberg

Let's take a look at how the function is actually used. As you can see above, we have initialized the variable $tool to the value that selectObject() returns. Note that we are not using the standard syntax for a variable assignment, but rather the reference-binding syntax introduced in my last column. Since selectObject() is a reference-returning function, we must treat $tool as a reference variable and assign it using the appropriate "=&" syntax. Once properly assigned, $tool now points to the same object as the first index of the $toolbox array $toolbox[0] and represents the instance of class A. The same process is used to assign the $anothertool variable to the instance of class B (we just pass false as the parameter, instead of true).

Although not particularly useful as shown, this method of using reference-returning functions is great when working with search trees or other complex data structures, by allowing the developer to search through the data structure and return a reference to the exact piece of data in question!

References in Object Constructors

Now that we've covered almost all there is to discuss regarding references, it's time to get to what probably is the most confusing reference phenomena -- referencing an object from within its constructor. Consider the following class:

<?php
    class test {
        function test($val) {
            global $myref;
            $myref = &$this;
            $this->value = $val;
        }
        function printval() {
            echo "The value of this class is '{$this->value}' <br>";
        }
        function setval($val) {
            $this->value = $val;
        }
    }
?>

Note that, in the constructor for this object, a global variable, $myref, is bound to a reference to $this (the pre-defined PHP reference to the object itself) and a member variable, $value, is set to the value of the passed parameter. When an instance of this class is created, a global variable, $myref, that points to this object will also be created. Hence, when this code is executed:

<?php
    $myvar = new test('FooBar!');
    $myvar->printval();
    $myref->printval();
?>

The output will be:

The value of this class is 'FooBar!'
The value of this class is 'FooBar!'

Now, what if we were to change the member variable within our instance of this class? From what we have learned thus far from references, any changes made through either the $myvar->setval() or $myref->setval() member functions should effectively change both. However, when the code below is executed:

<?php
    $myvar->setval('Changed the value from $myvar');
    $myvar->printval();
    $myref->printval();
?>

The resulting output is as follows:

The value of this class is 'Change the value from $myvar'
The value of this class is 'FooBar!'

Why didn't both change? The answer lies in when the object was first created. In PHP 4, the new statement does not return a reference by default. Rather, when the $myvar object was created, it returned a copy separate from the one referenced by the $myref variable. Thus, because they are separate instances of the same object, their variables are completely independent. To overcome this and achieve the desired result, we use the reference-binding operator when creating the objects, as shown:

<?php
    $myvar =& new test('Foobar!');
    $myvar->printval();
    $myref->printval();
    $myvar->setval('Now it works');
    $myvar->printval();
    $myref->printval();
?>

And the output:

The value of this class is 'Foobar!'
The value of this class is 'Foobar!'
The value of this class is 'Now it works'
The value of this class is 'Now it works'

That's All for Today

That's about everything there is to know about PHP references. From what I've shown you, you should be well on your way to using references to make your PHP scripts faster and more efficient, without using more code! Next week, I'll be changing gears and introducing some of the fundamental concepts around working with the browser to make your PHP pages more interactive and dynamic. See you then!

John Coggeshall is a a PHP consultant and author who started losing sleep over PHP around five years ago.


Read more PHP Foundations columns.

Return to the PHP DevCenter.


Copyright © 2009 O'Reilly Media, Inc.