What are the new features of PHP 8?

PHP 8.0 was a big release. It added many features that make code shorter and safer. Here are the main ones that are asked in interviews.

  • Named arguments: pass values by parameter name, for example new User(name: "Robin").
  • Constructor property promotion: declare and set properties in the constructor line.
  • Match expression: a stricter and shorter version of switch. See PHP match Expression.
  • Nullsafe operator (?->): stops the chain if the value is null.
  • Union types: a parameter or return can have more than one type, like int|string.
  • Attributes: add metadata to classes and methods using the #[...] syntax.
  • JIT compiler: can make some heavy calculations faster.
  • New functions: str_contains(), str_starts_with() and str_ends_with().
<?php
class User {
    public function __construct(public string $name, public ?string $city = null) {}
}

$user = new User(name: "Robin");   // named argument

echo $user->name . "<br>";
echo ($user?->city ?? "City not given") . "<br>";   // nullsafe operator
echo str_contains("Tutorials Class", "Class") ? "Found" : "Not found";
?>

Output:

Tutorials Class - Output Window

Robin
City not given
Found

Later versions added more, for example enums and readonly properties in PHP 8.1. Always check the version of PHP on your server before using a new feature.


Learn more about the similar topics:
Tutorials
PHP Introduction
PHP Terminology
PHP Installation
PHP Syntax
PHP Comments
PHP exit() Function
Exercises & Assignments
Write a program to print “Hello World” using echo
Simple Tips for PHP Beginners
Experiment with Basic PHP Syntax Errors
Using phpinfo() – Display PHP Configuration & Modules
Interview Questions & Answers
What is PHP?
Who is the father of PHP?
What is the correct & common way to start and finish a PHP block of code?
What is Open Source Software?
What is the default extension of the PHP file?
What is the latest version of PHP?
What is the full form of PHP?