Named Arguments in PHP 8


In PHP 7, we used to have positional parameters. That means, we need to assign the position of the first argument to the first parameter only. The default value is used for any missing arguments in PHP 7.x versions.

In PHP 8, we can pass the arguments to a function based on the parameter name, rather than passing the parameter position. Order doesn’t matter in PHP 8, it is allowed to skip default values randomly and it is also self-documenting.

Example − Named Arguments in PHP 8

  • In PHP 8, arguments are order-independent and self-documented.

  • We can skip the optional parameters but specify only the required parameters.

<?php
   function sample($num = 1, $value = 5){
      echo "Number: ", $num;
      echo " ";
      echo "Value: ", $value;
   }
   sample(value: 5, num: 30); //Named arguments in different order
?>

Output

Number: 30 Value: 5

In the function definition, argument names are matched with the parameter names. So, this code runs without any error.

Updated on: 01-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements