Adam Biro

Software Developer

Blogger

Photographer

Full Stack Developer

Photo Enthusiast

Web Developer

Adam Biro
Adam Biro

Software Developer

Blogger

Photographer

Full Stack Developer

Photo Enthusiast

Web Developer

Blog Post

[5] PHP8 New allowing class, Non-capturing catch, Trailing comma

April 24, 2022 IT, PHP, Programming
[5] PHP8 New allowing class, Non-capturing catch, Trailing comma

This is the fifth part of the series and in the current post, I want to go through the Allowing class on objects, Non-capturing catches, and Trailing comma in parameter lists. You can see the full list of features here. Furthermore, you can read the previous part of the series here.

Allowing class on objects

At the moment, in order to get the name of a class we need to use the get_class() method. You could use this feature as you can see below.

<?php
class foo {
}
// create an object
$bar = new foo();
// external call
echo "The name is " . get_class($bar) . "\n";
?>

With this new feature you will get the same result as you can see it:

<?php
class foo {
}
// create an object
$bar = new foo();
// external call
echo "The name is " . $bar::class . "\n";
?>

Non-capturing catches

Before PHP 8.0 we had to pass a variable in the catch side of the try-catch block even if we did not want to use it. So we had to write a code like this:

try {
    // Something goes wrong
} catch (MySpecialException $exception) {
    Log::error("Something went wrong");
}

With PHP 8.0 we can omit to pass that variable to the catch block.

try {
    // Something goes wrong
} catch (MySpecialException) {
    Log::error("Something went wrong");
}

Trailing commas in parameter lists

Before PHP 8.0 you could not add a comma at the end of the parameter list. In the new version of PHP, you can do that.

public function(
    string $parameterA,
    int $parameterB,
    Foo $objectfoo,
) {
    // …
}

New in PHP 8

Taggs: