PHP function argument refers to a value that is passed into a function when it is called. PHP Arguments supports Call by Value, Call by Reference, Default Argument Values and Variable-length argument.
1. Call by Value:
In Call by Value, the value of a variable is passed directly. This means if the value of a variable within the function is changed, it does not get changed outside of the function.
Example:
<?php
function increment($i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
Output:
10
2. Call by Reference:
In PHP, call by reference is a mechanism in which a function can directly modify the original value of a variable outside of the function. By default, function arguments are passed by value in PHP, which means that a copy of the argument’s value is passed to the function. However, you can pass arguments by reference using the &
symbol to allow the function to modify the original value of the variable.
Example:
<?php
function increment(&$i)
{
$i++;
}
$i = 10;
increment($i);
echo $i;
?>
Output:
11
3. Default Argument Values:
When you calling PHP function if you don’t specify any argument, it will take the default argument.
Example:
<?php
function Hello($name="Amit"){
echo "Hello $name <br>";
}
Hello("Abishek");
Hello();//passing no value
Hello("Vijay");
?>
Output:
Hello Amit
Hello Abhishek
Hello Vijay
4. Variable Length Argument:
It is used when we need to pass n number of arguments in a function. To use this, we need to write three dots inside the parenthesis before the argument.
Example:
<?php
function add(...$nums) {
$sum = 0;
foreach ($nums as $n) {
$sum += $n;
}
return $sum;
}
echo add(2, 4, 6, 8);
?>
Output:
20