New Features in PHP 8.2: Read‑only Classes, DNF Types, Stand‑alone null/false/true Types, and Constant Traits
The article introduces PHP 8.2’s major enhancements—including read‑only classes, disjunctive normal form (DNF) types, the ability to use null, false and true as independent types, and constant definitions inside traits—providing code examples that illustrate each new capability.
PHP is a widely used general‑purpose scripting language especially suited for web development, and PHP 8.2 brings a set of significant language improvements.
Read‑only Classes
Before PHP 8.2, properties could be declared readonly individually:
class BlogData {
public readonly string $title;
public readonly Status $status;
public function __construct(string $title, Status $status){
$this->title = $title;
$this->status = $status;
}
}Starting with PHP 8.2 a whole class can be marked as readonly , removing the need to repeat the keyword on each property:
readonly class BlogData{
public string $title;
public Status $status;
public function __construct(string $title, Status $status){
$this->title = $title;
$this->status = $status;
}
}Disjunctive Normal Form (DNF) Types
Prior to 8.2 developers had to emulate union/intersection logic with runtime checks:
class Foo {
public function bar(mixed $entity) {
if ((($entity instanceof A) && ($entity instanceof B)) || ($entity === null)) {
return $entity;
}
throw new Exception('Invalid entity');
}
}PHP 8.2 introduces true DNF syntax, allowing the parameter to be declared as an intersection or a union directly:
class Foo {
public function bar((A&B)|null $entity) {
return $entity;
}
}Standalone null, false and true Types
Earlier versions could only use null in nullable type declarations and could not express false or true as return types. PHP 8.2 adds them as first‑class types:
class Falsy{
public function alwaysFalse(): false { /* ... */ }
public function alwaysTrue(): true { /* ... */ }
public function alwaysNull(): null { /* ... */ }
}Constants in Traits
Traits can now contain constants, which can be accessed through classes that use the trait:
trait Foo{
public const CONSTANT = 1;
}
class Bar {
use Foo;
}
var_dump(Bar::CONSTANT); // int(1)
var_dump(Foo::CONSTANT); // Error: undefined constantFor a complete list of PHP 8.2 features, refer to the official release notes at php.net/releases/8.2/en.php .
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.