PHP Function arguments
Information may be passed to functions via the argument list.
PHP arguments are specified inside a parenthesis after function_name.
The PHP arguments are evaluated from left to right.
You can give multiple number of arguments as you want by separating them with comma(,).
PHP supports passing arguments by value, passing by reference, and default argument values.
Passing PHP arguments by value
1 2 3 4 5 6 7 8 9 10 11 |
<?php function sum($a, $b) { $c = $a + $b; echo $c; } sum(10, 20); sum(2, 4); ?> |
Output:
1 |
30 6 |
In above example function sum takes two arguments $a, $b.
When function called the $a is assigned by 10 and $b will assigned by 20.
Then it will perform summation and output addition.
When function sum call second time then it will perform addition of $a = 2 and $b = 4.
Passing arguments by reference
Lets see an example,
1 2 3 4 5 6 7 8 9 10 11 |
<?php $a = 10; function abc($a) { $a++; echo $a; } abc(10); echo $a; ?> /* Output: 11 10 */ |
As you can see in above example, a value of $a is not change outside the function.
Hence to allow a function to modify its arguments, they must be passed by reference.
The ampersand(&) is use before argument name in function definition to pass arguments by reference.
Example
1 2 3 4 5 6 7 8 9 10 11 |
<?php function con(&$str2) { $str2 .= 'string 2'; } $str1 = 'String1 concatenate with '; con($str1); echo $str1; ?> /* Output: String1 concatenate with string 2 */ |
In this example, a variable $str1 is passed to the function con().
The value of str1 is concatenate with the value of str2.