advertisement

[5] PHP 8.0 Allowing class on objects, non-capturing catches, and trailing comma in parameter lists

Learn about class usage on objects, non-capturing catches, and the trailing comma in parameter lists introduced in PHP 8.0.

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

The previous part of the series

PHP 8.0: Throw expression, Inheritance with private methods, Weak maps

advertisement