Professional Documents
Culture Documents
31PHP Named Arguments
31PHP Named Arguments
Since PHP 8.0, you can use named arguments for functions. The named arguments allow you to
pass arguments to a function based on the parameter names rather than the parameter positions.
The following example defines a function that finds the position of the first occurrence of a
substring in a string:
<?php
function find($needle, $haystack)
{
return strpos($haystack, $needle);
}
To call the find() function, you pass the arguments based on the parameter positions like this:
find('awesome', 'PHP is awesome!');
However, the function call is not apparent. For example, you do not know which argument is the
needle and which argument is the haystack.
Sometimes, you may accidentally make a mistake by passing the arguments in the wrong order.
For example:
find (
'PHP is awesome!',
'awesome'
);
This is buggy and very difficult to troubleshoot.
To avoid this, you may add comments to the arguments like this:
find (
'awesome', // needle
'PHP is awesome!' // haystack
);
The comment makes the code clearer. However, it is not robust.
To improve this, PHP 8.0 introduced the named arguments that allow you to specify the parameter
names when passing arguments:
find (
$needle : 'awesome',
$haystack : 'PHP is awesome!'
);
Since you are using the parameter names, the positions are not necessary. For example, you can
swap the parameters like this:
find(
$haystack :'PHP is awesome!',
$needle : 'awesome'
);
It should work correctly.
To create a link with the target is _blank, you must specify all the default arguments until the one
you want to change.
For example:
$link = create_anchor(
'PHP Tutorial',
'https://www.phptutorial.net/',
'',
'_blank'
);
echo $link;
Output:
<a href="https://www.phptutorial.net/" target="_blank">PHP Tutorial</a>
In this example, you need to pass the space (”) to the third argument. If you use the named
arguments, you do not have to specify all the defaults. For example:
$link = create_anchor(
text : 'PHP Tutorial',
href : 'https://www.phptutorial.net/',
target: '_blank'
);
Mixing named arguments with positional arguments
PHP allows you to call a function by using both positional arguments and named arguments. And
you need to place the named arguments after positional arguments.
For example:
$link = create_anchor(
'PHP Tutorial',
'https://www.phptutorial.net/',
target: '_blank'
);
In this example:
The text is 'PHP Tutorial'.
The href is 'https://www.phptutorial.net/'.
And the target is '_blank'.
If you place the named arguments before the positional arguments, you’ll get an error.
For example:
create_anchor(
target : '_blank',
'PHP Tutorial',
'https://www.phptutorial.net/'
);
Error:
Cannot use positional argument after named argument
Summary
• Use PHP named arguments to pass arguments to a function based on the parameter names.
• Put the named arguments after the positional arguments in function calls.