0
0
PHPprogramming~5 mins

Intersection types in practice in PHP

Choose your learning style9 modes available
Introduction

Intersection types let you say a value must follow multiple rules at the same time. This helps catch mistakes early and makes your code clearer.

When a function needs an object that has features from two or more different interfaces.
When you want to be sure a variable meets several type requirements before using it.
When combining traits or behaviors that must all be present in one object.
When you want to enforce strict type checks in your code for better safety.
Syntax
PHP
function exampleFunction(SomeInterface&AnotherInterface $param): void {
    // function body
}

Use the ampersand (&) to combine types.

The value must satisfy all types listed.

Examples
This function requires an object that can both log messages and write to a file.
PHP
<?php
interface Logger {
    public function log(string $msg): void;
}

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

function saveAndLog(Logger&FileWriter $obj, string $data): void {
    $obj->writeToFile($data);
    $obj->log('Data saved');
}
MyClass implements both interfaces, so it can be passed to the function.
PHP
<?php
class MyClass implements Logger, FileWriter {
    public function log(string $msg): void {
        echo "Log: $msg\n";
    }
    public function writeToFile(string $data): void {
        echo "Writing: $data\n";
    }
}

$obj = new MyClass();
saveAndLog($obj, 'Hello');
Sample Program

This program shows a Duck that can both fly and swim. The function moveAnimal requires an object that can do both, so it calls both methods.

PHP
<?php
interface CanFly {
    public function fly(): void;
}

interface CanSwim {
    public function swim(): void;
}

class Duck implements CanFly, CanSwim {
    public function fly(): void {
        echo "Duck is flying\n";
    }
    public function swim(): void {
        echo "Duck is swimming\n";
    }
}

function moveAnimal(CanFly&CanSwim $animal): void {
    $animal->fly();
    $animal->swim();
}

$duck = new Duck();
moveAnimal($duck);
OutputSuccess
Important Notes

Intersection types require PHP 8.1 or higher.

If the object does not implement all interfaces, PHP will give a type error.

Summary

Intersection types combine multiple type requirements using &.

They ensure a value meets all listed types.

Useful for functions needing objects with multiple capabilities.