This section provides a tutorial example on how to use pass-by-value arguments, which allows the function to re-assign new values to original variables in the calling code.
As we learned from the previous section, PHP functions use pass-by-value arguments by default.
If an argument is defined as an pass-by-value argument, the calling operation can provide an expression
for this argument. That expression will be assigned to this argument variable when function is called.
For example, if we have "function f($var) {...}" defined, "f(exp)" is equivalent to "{$var=exp; ...}".
To see how passing arguments by values works, I wrote this tutorial example, PassByValue.php:
<?php # PassByValue.php
# Copyright (c) 2003 by Dr. Herong Yang. http://www.herongyang.com/
#
function swap($left, $right) {
$temp = $left;
$left = $right;
$right = $temp;
print(" Swapped in function: ".getString($left, $right)."\n");
}
print("\n 1. Passing two literals:\n");
print(" Before call: ". getString("Apple", "Orange") ."\n");
swap("Apple", "Orange");
print("\n 2. Passing two variables:\n");
$x = "Dog"; $y = "Cat";
print(" Before call: ". getString($x, $y) ."\n");
swap($x, $y);
print(" After call: ". getString($x, $y) ."\n");
print("\n 3. Passing two arrays:\n");
$x = array("Mon", "Tue"); $y = array("Jan", "Feb");
print(" Before call: ". getString($x, $y) ."\n");
swap($x, $y);
print(" After call: ". getString($x, $y) ."\n");
print("\n 4. Passing two objects:\n");
$x = new DateTime("2005-01-01"); $y = new DateTime("2006-01-01");
print(" Before call: ". getString($x, $y) ."\n");
swap($x, $y);
print(" After call: ". getString($x, $y) ."\n");
function getString($left, $right) {
if (is_scalar($left)) {
return "$left | $right";
} elseif (is_array($left)) {
return "($left[0], $left[1]...) | ($right[0], $right[1]...)";
} elseif (is_object($left) && get_class($left)=="DateTime") {
return $left->format("Y")." | ".$right->format("Y");
} else {
return NULL;
}
}
?>
If you run this sample script, you should get:
1. Passing two literals:
Before call: Apple | Orange
Swapped in function: Orange | Apple
2. Passing two variables:
Before call: Dog | Cat
Swapped in function: Cat | Dog
After call: Dog | Cat
3. Passing two arrays:
Before call: (Mon, Tue...) | (Jan, Feb...)
Swapped in function: (Jan, Feb...) | (Mon, Tue...)
After call: (Mon, Tue...) | (Jan, Feb...)
4. Passing two objects:
Before call: 2005 | 2006
Swapped in function: 2006 | 2005
After call: 2005 | 2006
The output confirms that:
My swap() function is very powerful. It swapped anything received from the argument list.
Pass-by-value arguments can be used for scalars, arrays and objects.
Pass-by-value arguments are safe to use. The swap() function has no impact on calling code.