[2] Named arguments, Attributes, Match expression as new PHP8 features
In this second episode of the series, I want to go through the Named arguments, Attributes, and Match expressions as new PHP8 features. You can see the list of features here and if you want to check the first episode you can read that here.
Named arguments of PHP8
Named arguments are a practical feature, and it improves the readability of the code. It allows us to ignore the order of the function parameters because we can specify the param name.
function getNamedParams(string $a, string $b, ?string $c = null, ?string $d = null)
{ /* … */ }
getNamedParams(
b: 'value b',
a: 'value a',
d: 'value d',
);
Attributes
Attributes are annotations. We used annotation in PHP within the dock block section. We simulated the behavior in PHP in the comment section in the code. The new PHP version 8.0 provides a first-class citizen in the language to represent this kind of metadata.
The “first-class citizen” expression is usable because attributes are simple classes, annotated themselves with the #[Attribute] attribute; this base Attribute used to be called PhpAttribute in the original RFC but was changed with another RFC afterward.
use App\Attributes\ExampleAttribute;
#[ExampleAttribute]
class Foo
{
#[ExampleAttribute]
public const FOO = 'foo';
#[ExampleAttribute]
public $x;
#[ExampleAttribute]
public function foo(#[ExampleAttribute] $bar) { }
}
#[Attribute]
class ExampleAttribute
{
public $value;
public function __construct($value)
{
$this->value = $value;
}
}
Match expression in the PHP version 8
Match expression is a similar structure to the switch-case expression but it is on steroids. It is much shorter but provides the same logic as the switch.
Se let’s see the switch-case example first:
switch ($statusCode) {
case 200:
case 300:
$message = null;
break;
case 400:
$message = 'not found';
break;
case 500:
$message = 'server error';
break;
default:
$message = 'unknown status code';
break;
}
And this would be the match equivalent of the previous example:
$message = match ($statusCode) {
200, 300 => null,
400 => 'not found',
500 => 'server error',
default => 'unknown status code',
};