What if you could tell PHP exactly what combination of features an object must have, and it would check for you automatically?
Why Intersection types in practice in PHP? - Purpose & Use Cases
Imagine you have a function that needs an object which is both a Logger and a FileHandler. Without intersection types, you must manually check and combine these features, writing extra code to ensure the object meets both needs.
This manual approach is slow and error-prone because you have to write repetitive checks and casts. It's easy to forget one requirement, causing bugs that are hard to find. The code becomes messy and hard to maintain.
Intersection types let you declare that a parameter must satisfy multiple types at once. This means PHP can enforce the object has all needed features, making your code cleaner, safer, and easier to understand.
$obj = getObject(); if (!($obj instanceof Logger) || !($obj instanceof FileHandler)) { throw new Exception('Invalid object'); } $obj->log('message');
function process(Logger&FileHandler $obj) {
$obj->log('message');
}It enables writing functions that clearly require objects combining multiple roles, improving code safety and expressiveness.
For example, a system that logs errors to a file needs an object that is both a Logger and a FileHandler. Intersection types let you require exactly that, avoiding runtime errors.
Manual checks for multiple roles are slow and error-prone.
Intersection types let PHP enforce multiple type requirements at once.
This leads to cleaner, safer, and more understandable code.
Practice
A&B mean in PHP?Solution
Step 1: Understand intersection type concept
Intersection types require a value to meet all listed types at once, not just one.Step 2: Apply to
The value must be both type A and type B simultaneously.A&BFinal Answer:
The value must satisfy both type A and type B simultaneously. -> Option CQuick Check:
Intersection means AND, so both types required [OK]
- Confusing intersection (&) with union (|)
- Thinking it means either type A or B
- Assuming it means only one type
Countable and Iterator?Solution
Step 1: Recall intersection type syntax in PHP
PHP uses the ampersand (&) without spaces and escaped as & in HTML to declare intersection types.Step 2: Check each option
function process(Countable&Iterator $obj) {} usesCountable&Iteratorwhich is correct syntax for intersection types in PHP.Final Answer:
function process(Countable&Iterator $obj) {} -> Option AQuick Check:
Intersection uses & without spaces [OK]
- Using | instead of & for intersection
- Adding spaces around &
- Using comma instead of &
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);Solution
Step 1: Understand class C implements both interfaces
Class C implements both A and B, so it has methods foo() and bar().Step 2: Call test with intersection type parameter
Function test requires an object that is both A and B, which $c is. It calls foo() and bar() and echoes their results separated by space.Final Answer:
foo bar -> Option AQuick Check:
Object meets both interfaces, so output is 'foo bar' [OK]
- Expecting only one method output
- Thinking intersection causes error if both interfaces implemented
- Confusing union with intersection types
interface X { public function x(): void; }
interface Y { public function y(): void; }
function example(X&Y $obj) {
$obj->x();
$obj->y();
}
class Z implements X {
public function x(): void {}
}
$z = new Z();
example($z);Solution
Step 1: Check class Z interfaces
Class Z implements only interface X, not Y.Step 2: Analyze function parameter type
Function example requires an object implementing both X and Y (intersection). Passing $z violates this.Final Answer:
TypeError because $z does not implement interface Y. -> Option BQuick Check:
Intersection requires all interfaces, missing one causes TypeError [OK]
- Assuming partial interface implementation is enough
- Confusing syntax error with type error
- Thinking missing method causes fatal error instead of TypeError
JsonSerializable and Countable. You also want to ensure the object has a method customMethod(). Which of the following is the best way to type hint this in PHP 8.1+?Solution
Step 1: Understand intersection type usage
Use&to require both JsonSerializable and Countable interfaces.Step 2: Handle custom method not in interfaces
SincecustomMethod()is not part of these interfaces, check its existence withmethod_existsbefore calling.Final Answer:
function process(JsonSerializable&Countable $obj) { if (method_exists($obj, 'customMethod')) { $obj->customMethod(); } } -> Option DQuick Check:
Intersection + runtime check for extra method [OK]
- Using union (|) instead of intersection (&)
- Assuming method in interfaces without checking
- Ignoring type safety by using object without interfaces
Ready to prove it?
Pass the test and this pattern moves unknown
