Given a set of arguments whose length is unknown at present, we will see how a function can work with these unknown numbers of arguments whose quantity will vary depending on the requirement.
We will take up each word one by one to deeply understand the topic we are dealing with.
- Variable: It is the number of arguments keep changing.
- Length: It refers to the number of arguments.
- Argument: It refers input passed to a function.
Now, the point of interest lies at the word list, all the arguments passed at its call will go the function as an array. The values will be retrieved like they are being from an array.
Accessing Variable Arguments Method: In this, the function is made to accept variable arguments and work accordingly. The variable which has to have multiple numbers of arguments is declared with “…”(triple dots).
- Example:
<?php
function
sum(...
$numbers
) {
$res
= 0;
foreach
(
$numbers
as
$n
) {
$res
+=
$n
;
}
return
$res
;
}
echo
(sum(1,2,3,4).
"\n"
);
echo
(sum(5,6,1));
?>
- Output:
10 12
Providing Variable Arguments Method: You can also use “…”(triple dots) when calling functions to unpack an array or Traversable variable or literal into the argument list.
- Example:
<?php
function
add(
$a
,
$b
) {
return
$a
+
$b
;
}
echo
add(...[1, 2]).
"\n"
;
$a
= [1, 2];
echo
add(...
$a
);
?>
- Output:
3 3
Type hinted Variable Arguments Method: It is also possible to add a type of hint before the … token. If this is present, then all arguments captured by … must be objects of the hinted class.
- Example:
<?php
function
total_intervals(
$unit
, DateInterval ...
$intervals
) {
$time
= 0;
foreach
(
$intervals
as
$interval
) {
$time
+=
$interval
->
$unit
;
}
return
$time
;
}
$a
=
new
DateInterval(
'P1D'
);
$b
=
new
DateInterval(
'P2D'
);
echo
total_intervals(
'd'
,
$a
,
$b
).
' days'
;
?>
- Output:
3 days