Certified PHP Developer Learning Resources Value and reference passing

Learning Resources
 

Value and reference passing


Most methods passed arguments when they are called. An argument may be a constant or a variable. For example in the expression: Math.sqrt(x); The variable x is passed here.

Pass by Reference means the passing the address itself rather than passing the value and pass by value means passing a copy of the value as an argument.

This is simple enough, however there is an important but simple principle at work here. If a variable is passed, the method receives a copy of the variable's value. The value of the original variable cannot be changed within the method. This seems reasonable because the method only has a copy of the value; it does not have access to the original variable. This process is called pass by value.

pass a variable by reference to a function so the function can modify the variable. The syntax is as follows:

function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);
// $a is 6 here
?>
 

The following things can be passed by reference:

  • Variables, i.e. foo($a)
  • New statements, i.e. foo(new foobar())
  • References returned from functions, i.e.:

function foo(&$var)
{
    $var++;
}
function &bar()
{
    $a = 5;
    return $a;
}
foo(bar());
?>

 

 For Support