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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With