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.
Intersection types let you say a value must meet multiple type rules at once. It helps make your code safer by checking more conditions.
function example(SomeInterface&AnotherInterface $param): ReturnType&OtherType { // code }
<?php interface A { public function methodA(); } interface B { public function methodB(); } function test(A&B $obj) { $obj->methodA(); $obj->methodB(); }
<?php interface X {} interface Y {} function combine(X&Y $obj) { // This means $obj must be both X and Y (usually via traits or interfaces) }
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 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);
Intersection types were introduced in PHP 8.1.
They help catch errors early by requiring multiple type conditions.
Intersection types combine multiple types with &.
Values must satisfy all combined types.
Useful for requiring multiple interfaces or traits.
function example(SomeType&OtherType $param) {}SomeType&OtherType means the argument must be both SomeType and OtherType at the same time.interface A { public function foo(): string; }
interface B { public function bar(): string; }
class C implements A, B {
public function foo(): string { return 'foo'; }
public function bar(): string { return 'bar'; }
}
function test(A & B $obj) {
echo $obj->foo() . ' ' . $obj->bar();
}
$c = new C();
test($c);interface X { public function x(): void; }
interface Y { public function y(): void; }
class Z implements X {
public function x(): void {}
}
function foo(X & Y $param) {
$param->x();
$param->y();
}
$z = new Z();
foo($z);interface Logger { public function log(string $msg): void; }
interface FileWriter { public function write(string $data): void; }
class FileLogger implements Logger, FileWriter {
public function log(string $msg): void { echo "Log: $msg\n"; }
public function write(string $data): void { echo "Write: $data\n"; }
}
function process(Logger & FileWriter $obj, string $message) {
$obj->log($message);
$obj->write($message);
}
$fl = new FileLogger();
process($fl, "Hello World");Pass the test and this pattern moves unknown