| PHP - Passing Arguments to Functions | | Print | |
PHP - Passing Arguments to Functions
There are two ways you can pass arguments to a function: by value and by reference. To pass an argument by value, you pass in any valid expression. That expression is evaluated and the value is assigned to the corresponding parameter defined within the function. Any changes you make to the parameter within the function have no effect on the argument passed to the function. For example:
function triple($x) {
$x=$x*3;
return $x;
}
$var=10;
$triplevar=triple($var);
In this case, $var evaluates to 10 when triple() is called, so $x is set to 10 inside the function. When $x is tripled, that change does not affect the value of $var outside the function.
In contrast, when you pass an argument by reference, changes to the parameter within the function do affect the value of the argument outside the scope of the function. That's because when you pass an argument by reference, you must pass a variable to the function. Now the parameter in the function refers directly to the value of the variable, meaning that any changes within the function are also visible outside the function. For example:
function triple(&$x) {
$x=$x*3;
return $x;
}
$var=10;
triple($var);
The & that precedes $x in the triple() function definition causes the argument to be passed by reference, so the end result is that $var ends up with a value of 30.
| Users' Comments (0) |
|
No comment posted






