DEV Community

Saravana Sai
Saravana Sai

Posted on

PHP-8.0 Named Arguments - Explained in Depth

PHP supports passing arguments by 5 different types. They are

  1. Passing by reference (default type)
  2. Passing by value
  3. Default argument values
  4. Variable-length argument lists
  5. Named Arguments

First Lets Discuss. Why we need a named arguments.Let consider a example we are trying to write a function to calculate the house or home's monthly expenses . Some may have tax & water tax but,some may not.Let look a code with out using a named arguments.

<?php

function expense($food, $vatTax = 0, $electricity, $wTax = 0)
{
    return $food + $vatTax + $electricity + $wTax;
}

echo expense(20, 0 , 10, 10);  // user without vatTax

Enter fullscreen mode Exit fullscreen mode

In above function you can see even if the user not having a vatTax we are passing the zero. we can pass that as a last argument. for example we are passing like this.so , just think what if we have some more arguments for some reason it may need & not need.

This the case PHP-8.0 comes with Named Arguments where you can pass the arguments by name . let rewrite the above function using Named Arguments

<?php

function expense($food, $vatTax = 0, $electricity, $wTax = 0)
{
    return $food + $vatTax + $electricity + $wTax;
}

//passing arguments by name

echo expense(food: 40, electricity: 50); 


Enter fullscreen mode Exit fullscreen mode

So, using PHP named arguments we don't want to pass a default value for non used parameters.

Share your comments and like for more post like this.

Top comments (0)