A function gets information from outside via arguments. You can define any number of arguments—including 0 (none). These arguments need at least a name so they can be used inside the function; there cannot be two arguments with the same name. When invoking the function, you need to send the arguments in the same order as declared.
A function may contain optional arguments, that is, you are not forced to provide a value for those arguments. When declaring the function, you need to provide a default value for those arguments. So, in case the user does not provide a value, the function will use the default one.
function addNumbers($a, $b, $printResult = false) {
$sum = $a + $b;
if ($printResult) {
echo 'The result is ' . $sum;
}
return $sum;
}
$sum1 = addNumbers(1, 2);
$sum1 = addNumbers(3, 4, false);
$sum1 = addNumbers(5, 6, true); // it will print the result
This new function in the last example takes two
mandatory arguments and an optional one. The default value of the
optional argument is false
, and it is
then used normally inside the function. The function will print the
result of the sum if the user provides true
as the third argument, which happens only the
third time that the function is invoked. For the first two,
$printResult
is set to false
.
The arguments that the function receives are just copies of the values that the user provided. That means that if you modify these arguments inside the function, it will not affect the original values. This feature is known as sending arguments by value. Let's see an example:
function modify($a) { $a = 3; } $a = 2; modify($a); var_dump($a); // prints 2
We are declaring a variable $a
with value
2
, and then calling the modify
method sending that $a
. The modify
method
modifies the argument $a
, setting its
value to 3
, but this does not affect the
original value of $a
, which remains
2
as you can see from var_dump
.
If what you want is to actually change the
value of the original variable used in the invocation, you need to
pass the argument by reference. To do that, you add an ampersand
(&
) before the argument when
declaring the function:
function modify(&$a) { $a = 3; }
Now, on invoking the function modify
, $a
will always be
3
.
Note
Arguments by value versus by reference
PHP allows you to do it, and in fact, some native functions of PHP use arguments by reference. Remember the array sorting functions? They did not return the sorted array, but sorted the array provided instead. But using arguments by reference is a way of confusing developers. Usually, when someone uses a function, they expect a result, and they do not want the arguments provided by them to be modified. So try to avoid it; people will be grateful!