PHP 5.6 Three Point Functions with a Variable Number of Arguments Using the Syntax ... Deploying Arguments Using ...

Lecture



Functions with a variable number of arguments using the syntax ...

Functions with a variable number of arguments can now be implemented using the ... operator, instead of relying on func_get_args ().

<? 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

Deploying Arguments with ...

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
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)