Lecture
<? php
function f ($ req, $ opt = null, ... $ params) {
// $ params containing the remaining arguments.
printf ('$ req:% d; $ opt:% d; number of params:% d'. "\ n",
$ req, $ opt, count ($ params));
}
f (1);
f (1, 2);
f (1, 2, 3);
f (1, 2, 3, 4);
f (1, 2, 3, 4, 5);
?>
The result of this example:
$ req: 1; $ opt: 0; number of params: 0 $ req: 1; $ opt: 2; number of params: 0 $ req: 1; $ opt: 2; number of params: 1 $ req: 1; $ opt: 2; number of params: 2 $ req: 1; $ opt: 2; number of params: 3
Arrays and objects implementing the Traversable interface can be expanded into an argument list when passed to a function using the ... operator.
<? php
function add ($ a, $ b, $ c) {
return $ a + $ b + $ c;
}
$ operators = [2, 3];
echo add (1, ... $ operators);
?>
The result of this example:
6
Comments
To leave a comment
Running server side scripts using PHP as an example (LAMP)
Terms: Running server side scripts using PHP as an example (LAMP)