PHP 8.1 – Multi Classes Types

PHP 8.1 – Multi Classes Types

multi tool for classes selection

Combine two or more types of classes (or array) to be required by the class property, local variable or a return type of the function.

New support for pure intersection types are specified using the syntax T1&T2&... and can be used in all positions where types are currently accepted:

class A {
    private Traversable&Countable $countableIterator;
 
    public function setIterator(Traversable&Countable $countableIterator): void {
        $this->countableIterator = $countableIterator;
    }
 
    public function getIterator(): Traversable&Countable {
        return $this->countableIterator;
    }
}

This means it would not be possible to mix intersection and union types together such as A&B|C, this is left as a future scope.

More examples of union types:

function foo(): A&A {} // Disallowed
 
use A as B;
function foo(): A&B {} // Disallowed ("use" is part of name resolution)
 
class_alias('X', 'Y');
function foo(): X&Y {} // Allowed (redundancy is only known at runtime)
class A {}
class B extends A {}
 
class Test {
    public A&B $prop;
}
class Test2 extends Test {
    public B $prop;
}

More about PHP 8.1

Read about all PHP 8.1 features and changes in here.