PHP 8 - What's new in PHP 8

Last modified: April 08, 2022

enum

An enum is a special "class" that represents a group of constants. Adding enums will significant improve in PHP

enum Status{ case Pending; case Active; case Delete; }
Example
class Student { public setStatus(STatus $status): void { //... } } $student->setStatus(Status::Active)

Readonly properties

These properties can be only written once.

Example
class Student { public function __construct( public readonly string $location ) {} } $student = new Student('UK'); //error occur below as it can be only written once $student->$location = 'USA'

Final class constants

Example
// this is okay class Animal { public const X = "hello"; } class Cat extends Animal { public const X = "bar"; }
// this is NOT okay we add keyword final infront of property class Animal { final public const X = "hello"; } class Cat extends Animal { final public const X = "bar"; // error occur here }

Null-safe Operator

This provide safety in the method/property chanining when the return value or property can be null

Example
return $student->getAddress()?->getCountry()?->isoCode;