PHP: Pass By Reference vs. Pass By Value

By default, PHP is pass by value.

<?
function pass_by_value($param) {
  push_array($param, 4, 5);
}

$ar = array(1,2,3);

pass_by_value($ar);

foreach ($ar as $elem) {
  print "<br>$elem";
}
?>

The code above prints 1, 2, 3. This is because the array is passed as value.

<?
function pass_by_reference(&$param) {
  push_array($param, 4, 5);
}

$ar = array(1,2,3);

pass_by_reference($ar);

foreach ($ar as $elem) {
  print "<br>$elem";
}
?>

The code above prints 1, 2, 3, 4, 5. This is because the array is passed as reference, meaning that the function (pass_by_reference) doesn’t manipulate a copy of the variable passed, but the actual variable itself.
In order to make a variable be passed by reference, it must be declared with a preceeding ampersand (&) in the function’s declaration.

Source: http://www.adp-gmbh.ch/php/pass_by_reference.html


This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>