0
0
PHPprogramming~5 mins

Intersection types in PHP

Choose your learning style9 modes available
Introduction

Intersection types let you say a value must meet multiple type rules at once. It helps make your code safer by checking more conditions.

When a function needs an object that implements two or more interfaces.
When you want to ensure a variable is both a specific class and has certain traits.
When combining multiple type requirements for a parameter or return value.
When you want to be very clear about what types a value must satisfy.
Syntax
PHP
function example(SomeInterface&AnotherInterface $param): ReturnType&OtherType {
    // code
}
Use the ampersand (&) to combine types.
All types combined must be satisfied by the value.
Examples
This function requires an object that implements both interface A and B.
PHP
<?php
interface A {
    public function methodA();
}

interface B {
    public function methodB();
}

function test(A&B $obj) {
    $obj->methodA();
    $obj->methodB();
}
Intersection types can combine classes or interfaces, but usually used with interfaces.
PHP
<?php
interface X {}

interface Y {}

function combine(X&Y $obj) {
    // This means $obj must be both X and Y (usually via traits or interfaces)
}
Sample Program

This program shows a function that accepts an object that must be both a Logger and a FileWriter. The class FileLogger implements both, so it works.

PHP
<?php
interface Logger {
    public function log(string $msg): void;
}

interface FileWriter {
    public function writeToFile(string $content): void;
}

class FileLogger implements Logger, FileWriter {
    public function log(string $msg): void {
        echo "Log: $msg\n";
    }
    public function writeToFile(string $content): void {
        echo "Writing to file: $content\n";
    }
}

function process(Logger&FileWriter $obj) {
    $obj->log('Start');
    $obj->writeToFile('Data');
    $obj->log('End');
}

$fileLogger = new FileLogger();
process($fileLogger);
OutputSuccess
Important Notes

Intersection types were introduced in PHP 8.1.

They help catch errors early by requiring multiple type conditions.

Summary

Intersection types combine multiple types with &.

Values must satisfy all combined types.

Useful for requiring multiple interfaces or traits.