...

View Full Version : difference between value and reference in function calls with object arguments?



XmisterIS
01-04-2012, 11:35 AM
Consider the following code:



class myclass
{
public $value = 0;
}

$mc = new myclass;

function passByValue(myclass $cls)
{
$cls->value++;
}

function passByReference(myclass& $r_cls)
{
$r_cls->value++;
}

passByValue($mc);
passByReference($mc);

echo $mc->value."\n";


This code will output 2, as you would expect.

It seems to me that passByValue and passByReference are identical because objects are apparently passed by reference anyway. But ... is there actually any difference that I'm not aware of?

Fou-Lu
01-04-2012, 01:51 PM
No, there is a tremendous difference between pass-by-value, and pass-by-reference. When it comes to Objects in PHP5+, no reference is required. PHP uses a link identifier to access its objects, so it is still pass-by-reference and pass-by-value, the sole difference is another level of indirection. The end result is still the same identifier. This is a simple signature difference:


void passByValue(myclass *cls);
void passByReference(myclass **cls);

But we don't need to deal with the indirection level in PHP.

You can only see this difference when it comes to direct assignments:


<?php
class myclass
{
public $value = 0;
}
$aHash = array();
$mc = new myclass;

function passByValue(myclass $cls)
{
$cls = new myclass();
$cls->value = __FUNCTION__;
return $cls;
}

function passByReference(myclass& $cls)
{
$cls = new myclass();
$cls->value = __FUNCTION__;
return $cls;
}

$obj = passByValue($mc);
//$obj2 = passByReference($mc);

echo $mc->value. PHP_EOL;
print $obj->value . PHP_EOL;
print $obj2->value . PHP_EOL;


$mc will have a value of 0. $obj will have a value of 'passByValue'. If you uncomment the $obj2 call, $mc and $obj2 will have a value of 'passByReference' and $obj will have a value of 'passByValue'.

XmisterIS
01-04-2012, 02:42 PM
I gotcha! Seeing the two C-style signatures at the top makes it make sense!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum