Variadic Functions

Last updated on

PHP Variadic functions offer a flexible way to handle a variable number of arguments within a function. With variadic functions, you can create more versatile and dynamic code.

In PHP, variadic functions are designed to accept a variable number of arguments through the use of the spread operator “…” in the function parameter.

Now, let’s take a look at the syntax.

Syntax of Variadic Functions

When declaring a variadic function, integrate the ellipsis (…) before the last variable parameter in the function signature. For example:

function name( ...$param ) {
  // .... Your code here
}

Now, in the following section, we will delve deeper into how it operates within functions.

How the Variadic Functions Work in PHP

In PHP, variadic functions are defined by employing the three dots operator before the function parameter. This enables the function to accept an unlimited number of arguments when invoked elsewhere in the code.

These variadic functions bear resemblance to the built-in function func_get_args(), responsible for retrieving all the arguments passed to a function. However, the key distinction lies in variadic functions allowing you to specify the arguments directly in the function signature, contributing to code conciseness and improved readability.

For example.

<?php
   function mul( $number1, $number2 ) {
     $args = func_get_args();
     print_r($args);
   }
   mul(55, 16);
?>

In this example, the output would be an array as shown below.

Array ( [0] => 55 [1] => 16 )

This implies that func_get_args() captures all the arguments passed into the function when invoked in other sections of the code.

variadic function

PHP variadic functions perform the same function by allowing the use of the three dots operator before the function parameter to accept a variable number of arguments.

To define a new variadic function, you simply need to add the three dots before the function parameter, as in the following example:

<?php
   function mul( ...$numbers ) { 
     print_r($numbers);
   }
   mul(55, 16);
?>

It will print the same result as the previous example. Now, let’s delve into a few more examples.

Examples of PHP Variadic Functions

This variadic function concatenates all the provided arguments.

<?php
function variadic_func( ...$param ) {
   $string = '';
   if( count( $param ) ) { 
      for( $i=0; $i<count($param); $i++ ) {
         $string .= $param[$i];
         $string .= " ";
      }
   }
 
   return $string;
}
$welcome = variadic_func( "Welcome", "to", "CodedTag", "Tutorials" );
echo $welcome;
?>

The output: Welcome to CodedTag Tutorials

Using the variadic function with a type hinting.

<?php
   function func( Object ...$obj ) {
     print_r( $obj );
   }
   func([1, 2, 3]);
?>

This will show you an error as shown below.

Fatal error: Uncaught TypeError: func(): Argument #1 must be of type object.

To address this error, ensure that you pass arguments of the same data type.

<?php
   $obj = (object) [1, 2, 3];
   func($obj);
?>

The output:

Array ( [0] => stdClass Object ( [0] => 1 [1] => 2 [2] => 3 ) ) 

Unpack an array into arguments using the variadic function.

<?php
  function table( $w, $x, $y, $z ) {
     echo ( ($w + 20 ) - ( $y + $z ) );
  }

  table(10, ...[20, 30, 40]); // -40
?>

The variadic parameter must be the last parameter in the function, otherwise, an error will occur. For example:

<?php
  function table( ...$x, $y ) {
      // ...
  }

  table(10, 10);  
?>

This will show you an error as shown below.

Fatal error: Only the last parameter can be variadic in index.php

The correct syntax would be as follows:

<?php
  function table( $y, ...$x ) {
      // ...
  }

  table(10, 10);  
?>

Wrapping Up

Variadic functions in PHP allow you to accept a variable number of arguments by using the three dots operator before the function parameter. This means that you can pass an unlimited number of arguments into the function when you call it in other parts of your code.

To prevent fatal errors, the variadic parameter must always be placed at the end of the function parameter list. This ensures that the function can correctly parse the arguments and avoid any errors that may occur.

Variadic functions were introduced in PHP 5.6 as a new feature that allows developers to write more flexible and powerful code. By using variadic functions, you can make your code more concise and easier to read.

In addition to passing individual arguments, you can also unpack an array into a variadic function. For example, you can call a function and pass an array of arguments like this: callback($var, ...['va', 'ca']). This will unpack the array and pass its values as separate arguments to the function.

When you define a variadic function in PHP, the variadic parameter is treated as an array within the function. This means that you can loop through the arguments and perform operations on them as needed.

Share on: