Wednesday, January 13, 2010

PHP Variables passed by value or by reference?

//PHP Variables passed by value or by reference?
//
//Variable is passed by value.
// for PHP5 Object passed by Reference, Object handler (Object variable) passed by // value

// for PHP4 Object passed by value, Object handler (Object variable) passed by value

//example

function test1($a) {
$a=2;
}

function test2(&$a) {
$a=2;
}

$a = 1;
echo $a; // output 1
test1($a);
echo $a; // output 1
// as variable is passed by value

//case for passed by reference
$a = 1;
echo $a; // output 1
test2($a);
echo $a; // output 2
// as variable is passed by reference

// now interesting case about objects
// in PHP 5 Object are always passed by reference
// in PHP 4 Object are passed by value
// object handler (Object variables) are passed by value
// see example
class Test {
var $strVal = 1;

function getValue() {
return $this->strVal;
}
}

function test($obj) {
echo $obj->getValue();
$obj->strVal = 2;
}

// now test cases
$obj1 = new Test();
test($obj1);
echo " ".$obj1->strVal;
// output 1 2 (In PHP5)
// output 1 1 (In PHP4)

// now explanation
// $obj1 is new object created. $obj1 is represent the handler for that new object
// test is called then handler is passed by value and object is passed by reference
// so $obj1 and $obj are object handler pointing to same object
// so you will get out put as 1 2 in PHP 5
// in case of PHP4 output will be 1 1 because object passed by values
// so $obj1 and $obj are two object handler pointing two different instances of Test class.


// now for PHP 4 if you want to pass object as reference then just changes test method as // follows
// add the & sign before parameter

function test(&$obj) {
echo $obj->getValue();
$obj->strVal = 2;
}

No comments: