PHP supports passing arguments by 5 different types. They are
- Passing by reference (default type)
- Passing by value
- Default argument values
- Variable-length argument lists
- 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
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);
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)