Questions And Answers

More Tutorials

PHP Functions

PHP 5.6 introduced variable-length argument lists (a.k.a. varargs, variadic arguments), using the ... token before the argument name to indicate that the parameter is variadic, i.e. it is an array including all supplied parameters from that one onward.

function variadic_func($nonVariadic, ...$variadic) {
 echo json_encode($variadic);
variadic_func(1, 2, 3, 4); 



Type names can be added in front of the ...:

function foo(Bar ...$bars) {}

The & reference operator can be added before the ..., but after the type name (if any). Consider this example:
class Foo{}
function a(Foo &...$foos){
 $i = 0;
 foreach($a as &$foo){ // note the &
 $foo = $i++;
$a = new Foo;
$c = new Foo;
$b =& $c;
a($a, $b);
var_dump($a, $b, $c);



On the other hand, an array (or Traversable) of arguments can be unpacked to be passed to a function in the form of an argument list:



string(3) "md2"
string(3) "md4"
string(3) "md5"

Compare with this snippet without using ...:


array(46) {
string(3) "md2"
string(3) "md4"

Therefore, redirect functions for variadic functions can now be easily made, for example:
public function formatQuery($query, ...$args){
 return sprintf($query, ...array_map([$mysqli, "real_escape_string"], $args));

Apart from arrays, Traversables, such as Iterator (especially many of its subclasses from SPL) can also be used.
For example:
$iterator = new LimitIterator(new ArrayIterator([0, 1, 2, 3, 4, 5, 6]), 2, 3);
echo bin2hex(pack("c*", ...$it)); 



Function Scope

Variables inside functions is inside a local scope like this

$number = 5
function foo(){
 $number = 10
 return $number


Will print 10 because text defined inside function is a local variable


In this page (written and validated by ) you learned about PHP Functions . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP String interpolation.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.