Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Passing by Reference Avoid Creating New Variable?

Tags:

oop

php

If I pass a variable or object to a function call by reference, I would imagine it avoids creating a second object in memory, thus preserving resources? For example:

<?php

class CoolObject
{
    // Have some properties here

    public function __construct()
    {
       // Do some stuff
    }

    public function test()
    {
       echo("Test");
    }
}

function doSomething(&$param)
{
   // Calls original instance, still only one object in memory
   $param->test();

   // Does this create a second instance in memory, or just assign
   // the reference?
   $newObj = $param;
}

// Create 1st instance of object in memory
$myObj = new CoolObject;

// Do a test to determine number of instances created
doSomething($myObj);

?>

When I assigned the "by reference" variable to $newObj, did it create a new one in memory bringing the count up to two, or did it just pass the reference still leaving only one object?

like image 580
Jeremy Harris Avatar asked Feb 02 '12 22:02

Jeremy Harris


1 Answers

If you pass in a variable by reference, you are correct in that it does not duplicate the object. Instead, it copies the pointer to the object. So, while it uses some memory, it's only the amount of memory equal to the size of a pointer.

When you create another variable that points to the same object, again, you're copying the pointer, with the same consequences as above.

As far as reference counting and objects, each time you copy the pointer, the reference counter gets incremented.

Only when the reference count is zero does the object get freed.

like image 55
Marcus Adams Avatar answered Oct 12 '22 22:10

Marcus Adams