Im looking for a bit of advice, I have visited this page in the manual, however it might be the wrong page or I misinterpreted the instructions as I am still confused.
I have the following question about the assignment above. I would like to know:
Thank you for reading
PHP has support for variable-length argument lists in user-defined functions. This is implemented using the ... token in PHP 5.6 and later, and using the func_num_args(), func_get_arg(), and func_get_args() functions in PHP 5.5 and earlier.
http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list
Here is for 5.6+
<?php
function my_func(...$parameters)
{
echo "There were ".count($parameters)." parameters passed:\n";
foreach ($parameters as $a_parameter)
{
echo "Number ".$a_parameter."\n";
}
}
echo my_func(1, 2, 3, 4, 5);
?>
https://3v4l.org/QuJqD
In (even more) simple words:
The magic happens with the ...
token. my_func
expects a variable number of parameters, which will be stored in the $parameters
array. All that because of the ...
that precedes the $parameters
. Then by using count
on that $parameter
array we get the number of the parameters stored in that array.
As Steven in the comments nicely put it: my_func(...$parameters)
has a variable length parameter list as opposed to a fixed-length parameter list which would look like function my_func($param1, $param2, $param3, $param4, $param5)
which would always expect 5 parameters.
To use variable length parameters on PHP you need the function func_get_args()
instead to define the parameters on function declaration. Your function look like this:
function foo()
{
$params_count = func_num_args();
$params_values = func_get_args();
}
On $params_values
there are all parameters which were given to the foo()
function. On params_count
there is the number of parameters given to foo()
. You can get the number of parameters given to the foo function with func_num_args()
An example of using this functions (https://3v4l.org/TWd3v):
function foo() {
$params_count = func_num_args();
var_dump($params_count);
$params_values = func_get_args();
var_dump($params_values);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With