Since PHP 8.0, we can use union types, where the value should be one of the specified types. Since PHP 8.1, we can use intersection types, where the value should belong to all the specified class and interface types.
Since PHP 8.2, we can use DNF (Disjunctive Normal Form) types. It means that union and intersection types can be combined. When defining DNF type, intersection types must be grouped with brackets.
(class_1&class_2&...&class_n)|type_1|type_2|...|type_n
DNF types are allowed anywhere types are accepted: parameters, return values, and properties. The most common use case is to declare DNF type that accepts intersection type or null
value.
<?php
class Storage
{
private (ArrayAccess&Countable)|null $container;
public function getContainer(): (ArrayAccess&Countable)|null
{
return $this->container;
}
public function setContainer((ArrayAccess&Countable)|null $container): void
{
$this->container = $container;
}
}
In this case, (ArrayAccess&Countable)|null
is the DNF type. The $container
parameter can be an instance of the class that implements both ArrayAccess
and Countable
interfaces, or null
value.
Redundant types
Redundant types are not allowed. For example, the following type declaration is illegal and produce a fatal error:
(ArrayAccess&Countable)|(Countable&ArrayAccess)
Leave a Comment
Cancel reply