In the previous article, we learned about passing parameters by reference in passing parameters to functions. If you need it, please read "How to pass parameters by reference in PHP functions?" 》. This time we introduce to you two other methods of passing parameters to functions. You can refer to them if you need them.
There are four ways to pass parameters to a function, namely value passing, reference passing, default parameters and variable length parameters. The previous two articles introduced value passing and reference passing. This time we will introduce default parameters and variable length parameters.
Default parameters
First let’s look at a small example.
<?php function add($a, $b=56){ echo $a.' + '.$b.' = '.($a+$b).'<br>'; } add(11); add(37, 29); ?>
The output result is
11 + 56 = 67 37 + 29 = 66
This example can clearly see that when the provided parameter is one and the other parameter has a default value, the operation will be performed directly; if the provided If there are two parameters, the operation will be performed based on the provided values.
Default parameters specify default values for one or more formal parameters of the function. If the corresponding value is not passed in when calling the function, the function will use this default value, which can avoid errors when calling without parameters and make some programs more reasonable. If the corresponding parameter is passed in, the default value will be replaced.
Variable length parameters
Let’s give a small chestnut first.
<?php function test(...$arr){ print_r($arr); } echo '<pre class="brush:php;toolbar:false">'; test(1, 2, 3, 4); test(5, 6, 7, 8, 9, 10); ?>
The output result is
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 8 [4] => 9 [5] => 10 )
This example can clearly see that the parameter values provided to the function twice are different, but observing the results, you will find that all the input values are output. We look at the function itself and see that it is different from a normal function in that it has "...
" added. This is a great feature of variable length parameters.
In PHP 5.6 and later versions, the formal parameters of a function can use... to indicate that the function can accept a variable number of parameters, and the variable parameters will be passed to the function as an array.
All the PHP knowledge you want is here→php video tutorial
The above is the detailed content of How to pass default parameters and variable length parameters in php functions?. For more information, please follow other related articles on the PHP Chinese website!