Named Arguments in PHP.

Burhan Shah
2 min readJul 18, 2022

--

Named arguments are something I was long awaiting in PHP. As of now, since PHP 8.0.0, we have it.

Have you ever created a function or method with multiple arguments and didn’t always need to pass them all or wanted to skip the default valued arguments when called but always had to because of the order of the arguments? Let’s look at an example:

//Lets say we have a function like thisfunction getSomething($needsACheck = true, $someValue = null){   if($needsACheck){
if($someValue = 'value'){
echo "Its a match!";
}else{
echo "We've got nothing";
}
}else{
echo "It'll always match";
}
}

In the above example, we have a function that has two optional arguments. For most of our cases whenever we pass $someValue, $needsACheck will always be true. Without named arguments we will always have to pass both the parameters just as below:

getSomething(true, 'value');

In the above case, the arguments are order-dependent. But with named arguments, we can make the call order-independent and only pass what is required.

getSomething(someValue: 'value')

The syntax to pass a named argument is the name of the parameter followed by a colon and then the value for the argument

In the above example, we only wanted to pass the second argument, so we just prefixed the value with the parameter name and a colon, ‘someValue:’.

Also, a point to note is, that you can make use of reserved keywords for your parameter names but you can’t use dynamic values. It has to be an identifier.

function mux($int = 2, $float = 0){
return $int*$float;
}
echo mux(float: 2.2); //This will work/*-----------------------------------*/$argumentName = 'someValue';getSomething($argumentName: 'value') // this will result in an error

Hope this helps some bit.

Happy Coding!

--

--