Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Intersection types in PHP 8.1

When working with types in any language there is a couple of scenarios that can occur.

  • Allow properties to be typed using multiple different types where the property must match at least one of the types.
  • Allow properties to be typed using multiple different types where the property must match all of the types.

PHP has been already supporting the first scenario in form of union types since PHP 8.0 where you can type the properties using multiple types like so.

class Number
{
    private int|float $number;

    public function setNumber(int|float $number): void
    {
        $this->number = $number;
    }

    public function getNumber(): int|float
    {
        return $this->number;
    }
}

But the thing that was not supported is the second scenario and that is what PHP 8.1 is trying to solve (at least partially) in form of intersection types.

Pure Intersection Types

Since the release of PHP 8.1, it’s now possible to combine multiple types into one intersection (using the syntax T1&T2&...) where the property must match all the types that is been assigned to it.

So, something like this is possible now.

function countAndIterate(Iterator&Countable $value)
{
    foreach ($value as $val) {
        echo $val;
    }

    count($value);
}

As you can tell, here the $value input must be of the type Iterator and Countable. Failing to do so results in a TypeError.

The catch(es)

But there’s a slight catch in here. Currently, only class types (interfaces and class names) are supported by intersection types due to some of the edge cases. So, it’s not possible to create an intersection type of the standard types such as int, float, string, and so on.

That means we are left with creating intersection types using class types only.

Apart from this, it’s also not possible to mix match intersection types and union types. So, something like the following is not possible.

Iterator&Countable|SplFileInfo

The possibility to do so has been left for the future scope. So, fret not!

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?