PHP Function Arguments Passing
How to Passing Arguments to Function?
Explanation
The arguments can be passed to a function, using arguments list seperated by commas. Arguments can passed in two ways one is "Passing by Reference" other is "Passing by Value"
Passing by Value:
Arguments are passed by value as default in PHP, and the value is assigned directly in the function definition.
Example :
<?php
function fruit($type = "cherry")
{
return "Fruit you chose is $type.";
}
echo fruit();
echo "<br>";
echo fruit(null);
echo "<br>";
echo fruit("Strawberry");
?>
Result :
Fruit you chose is cherry.
Fruit you chose is .
Fruit you chose is Strawberry.
In the above example value "cherry" is passed to the function fruit, even values can be passed directly as in the last example.
Passing By Reference:
Passing the address itself rather than passing the value to the function is Passing by Reference.
Example :
<?php
function fruit(&$string)
{
$string .= 'Cherry';
}
$str = 'This is the fruit, ';
fruit($str);
echo $str;
?>
Result :
This is the fruit Cherry
In the above example the value is assigned for "$string" inside the function. Usually in passing by reference a copy of the variable is modified, rather than a variable itself as in passing by value. So it is suitable for large codes.