PHP 8 fresh exciting features — part 2
PHP 8 is going to get released in less than a day now. I’ve written some of its exciting new features in my previous article, you can check it out.
There are other interesting features that I’m going to talk about in this story, so rev up your PHP engines and let’s review them in action!
Match Expression
As you might already know, the switch statement in PHP has some flaws, such as type coercion and not having a return value.
Fortunately, a new control structure named match is coming to make previous problems fade away.
$result = match (5) {
1 => 'One',
2 => 'Two',
5 => 'Five',
6 => 'Six',
};
echo $result;
// Five
Apart from simplicity, the match statement comes with some perks:
- You can return the matched expression as a value.
- The switch statement uses double equals (==) that can result in some unwanted situations. but the match expression uses triple equals (===).
- No need to use the break word every time.
Constructor promoted properties
Ever done the following thing? of course!
class Rectangle
{
public int $width;
public int $height;
public function __construct(
int $width = 0, int $height = 0
)
{
$this->width = $width;
$this->height = $height;
}
}
The main problem with the code above is repetition.
With promoted properties, comes the ability to prevent all repetition:
class Rectangle
{
public function __construct(
public int $width = 0,
public int $height = 0
) {}
}
As you can see, this is much more simple and readable, but there are some places you cannot use this feature. for example, promoted properties cannot happen in abstract constructors.
You can find a long list of dos and don’ts regarding this feature here.
Non-capturing catches
At this time, PHP requires to pass the exception caught into a variable:
try {
somethingRiskyHere();
} catch (JsonException $jsonException) {
// do something about the exception!
}
But what if you don’t want to use the variable that contains the caught exception? prior to PHP 8, you couldn’t do this. but now you can skip specifying the variable:
try {
somethingRiskyHere();
} catch (JsonException) {
// do something about the exception!
}
PHP 8 is coming officially in a few hours, you can check the full list of its new features in PHP wiki. Tomorrow will be a new day for PHP developers!