Home
Web design
Software
Articles
Site Map

> Articles > PHP articles > Checking if two variables are references to the same object

Checking if two variables are references to the same object

  • 1. Introduction.

References is very usefull feature of PHP, allowing execution time and required memory optimization. They behave almost like references in the C language.

References allow us to avoid unnecessary creation of several copies of the same variable. Example:

    $a 10;
    
$b = &$a// starting from here, $b references the same data as $a
    
$b 5;
    echo 
$a// it will output 5

Also references may be usefull for creating complex data structures in memory. Example of tree data structure:

    class CTree
    
{
        var 
$aChildren// array of child branches
        
var $refParent// reference to the parent branch
        
var $data// data of this branch

        /* Function do add child to this branch. Passing $data by reference
        to avoid unnecessary memory usage and time for copying the data. */
        
function AddChild($name, &$data)
        {
            
$this->aChildren[$name] = new CTree();
            
$this->aChildren[$name]->data $data;
            
$this->aChildren[$name]->refParent = &$this;
        }
    }

Imagine what would happen if having references to two objects of class CTree we compare them (trying to find out if they reference the same branch of not). PHP will start comparing all it's member variables and their member variables, and since referece to the parent object is also a member variable, we will end up with a infinite loop.

  • 2. Definition of the problem.

We need a method to check if two variables reference the same data.
PHP doesn't allow us to do that in a straight way.
  • 3. Solution.

Here's a workaround which will work for references to objects.
It uses PHP feature that allows to create object member variables not specified in the class to which object belongs.

For instance:

    class CMyClass
    
{
        var 
$a;
    };
    
$object = new CMyClass();
    
$object->10// using member variable defined in the class.
    
$object->"test"// here creating and using new member variable.

Let us have variables $a and $b and we want to find out if they are references to the same object, or not.

All we have to do now is to create a new member variable in $a and then to chech if that member variable exists in $b. If that new member variable also appears in $b, then both $a and $b reference the same object.

    function comparereferences(&$a, &$b)
    {
        
// creating unique name for the new member variable
        
$tmp uniqid("");
        
// creating member variable with the name $tmp in the object $a
        
$a->$tmp true;
        
// checking if it appeared in $b
        
$bResult = !empty($b->$tmp);
        
// cleaning up
        
unset($a->$tmp);
        return 
$bResult;
    }



Copyright © Val Samko, DigiWays. Written by Valentin Samko mailto:val@digiways.com