Answer
Named arguments are a new feature in PHP 8.0.
In functions or methods with simple signatures it can serve as a sort of self-documentation to indicate what the arguments are. For example in the code you provided, both arguments are simple callbacks that perform basic string manipulation on the provided value. Without the argument names, someone reading the code would need to check the method signature to know what each argument does.
It’s also a convenient way to only specify needed arguments when using functions or methods with long signatures or complex default values.
For example, the signature for htmlspecialchars()
looks like this:
htmlspecialchars(
string $string,
int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401,
?string $encoding = null,
bool $double_encode = true
): string
In previous versions if you wanted to change the double_encode
argument to false, but leave the other arguments as default, you’d have to do this:
<?php
htmlspecialchars(
"Some text & stuff",
ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401,
null,
false
);
But with named arguments it looks like this:
<?php
htmlspecialchars(
"Some text & stuff",
double_encode: false
);
0 comments:
Post a Comment
Thanks