Bird
Raised Fist0
PHPprogramming~10 mins

Intersection types in practice in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Intersection types in practice
Define Interfaces
↓
Create Class implementing both
↓
Function requires intersection type
↓
Pass object to function
↓
Function uses methods from both interfaces
↓
Output result
This flow shows how PHP uses intersection types to require an object to implement multiple interfaces before passing it to a function.
Execution Sample
PHP
<?php
interface A { function foo(): string; }
interface B { function bar(): string; }
class C implements A, B {
  function foo(): string { return "foo"; }
  function bar(): string { return "bar"; }
}
function test(A&B $obj): string {
  return $obj->foo() . " & " . $obj->bar();
}
$obj = new C();
echo test($obj);
This code defines two interfaces, a class implementing both, and a function requiring an intersection type to call methods from both interfaces.
Execution Table
StepActionEvaluationResult
1Define interface A with method foo()Interface A createdInterface A available
2Define interface B with method bar()Interface B createdInterface B available
3Define class C implementing A and BClass C created with foo() and bar()Class C available
4Create object $obj = new C()Object $obj createdInstance of C with foo() and bar()
5Call test($obj) with intersection type A&BCheck if $obj implements A and BTrue, proceed
6Inside test(), call $obj->foo()Call foo() method"foo" returned
7Inside test(), call $obj->bar()Call bar() method"bar" returned
8Concatenate results "foo & bar"Combine strings"foo & bar"
9echo test($obj)Output to screenfoo & bar
10End of scriptNo more codeExecution stops
💡 Script ends after outputting 'foo & bar'
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 8Final
$objundefinedInstance of CInstance of CInstance of CInstance of C
Return value of test()undefinedundefinedundefined"foo & bar""foo & bar"
Key Moments - 3 Insights
Why does the function test() require the parameter type A&B instead of just A or B?
Because test() uses methods from both interfaces A and B, the parameter must implement both. The intersection type A&B ensures the object has all required methods, as shown in execution_table step 5.
What happens if we pass an object that implements only interface A to test()?
The type check in step 5 fails because the object does not implement B. PHP will throw a TypeError and stop execution before calling foo() or bar().
How does the class C satisfy the intersection type A&B?
Class C implements both interfaces A and B by defining both foo() and bar() methods, so an instance of C can be passed to test() as shown in steps 3 and 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 6, what method is called on $obj?
Abar()
Bfoo()
Ctest()
DNone
💡 Hint
Check the 'Action' and 'Evaluation' columns at step 6 in the execution_table.
At which step does the function test() confirm that $obj implements both interfaces A and B?
AStep 7
BStep 4
CStep 5
DStep 9
💡 Hint
Look for the step where the intersection type check happens in the execution_table.
If class C did not implement interface B, what would happen at step 5?
APHP would throw a TypeError
BThe method foo() would not be called
CThe function test() would run normally
DThe script would output 'foo & bar'
💡 Hint
Refer to key_moments about what happens if the object does not satisfy the intersection type.
Concept Snapshot
Intersection types in PHP require an object to implement multiple interfaces.
Syntax: function f(A&B $obj) requires $obj to implement both A and B.
Use when a function needs methods from multiple interfaces.
If object lacks any interface, PHP throws a TypeError.
Class can implement multiple interfaces to satisfy intersection types.
Full Transcript
This example shows how PHP uses intersection types to require an object to implement multiple interfaces before passing it to a function. Two interfaces A and B are defined, each with one method. Class C implements both interfaces by defining both methods. The function test() requires a parameter that implements both A and B, using the intersection type A&B. When an instance of C is passed to test(), it calls both methods foo() and bar() and concatenates their results. The execution table traces each step from defining interfaces and class, creating the object, checking the intersection type, calling methods, and outputting the result. Key moments clarify why intersection types are needed and what happens if the object does not satisfy them. The visual quiz tests understanding of method calls, type checks, and error conditions. The concept snapshot summarizes the syntax and behavior of intersection types in PHP.

Practice

(1/5)
1. What does an intersection type like A&B mean in PHP?
easy
A. The value must be type B only.
B. The value can be either type A or type B.
C. The value must satisfy both type A and type B simultaneously.
D. The value must be type A only.

Solution

  1. Step 1: Understand intersection type concept

    Intersection types require a value to meet all listed types at once, not just one.
  2. Step 2: Apply to A&B

    The value must be both type A and type B simultaneously.
  3. Final Answer:

    The value must satisfy both type A and type B simultaneously. -> Option C
  4. Quick Check:

    Intersection means AND, so both types required [OK]
Hint: Intersection means all types must be met together [OK]
Common Mistakes:
  • Confusing intersection (&) with union (|)
  • Thinking it means either type A or B
  • Assuming it means only one type
2. Which of the following is the correct syntax for declaring a function parameter with an intersection type of interfaces Countable and Iterator?
easy
A. function process(Countable&Iterator $obj) {}
B. function process(Countable|Iterator $obj) {}
C. function process(Countable, Iterator $obj) {}
D. function process(Countable & Iterator $obj) {}

Solution

  1. Step 1: Recall intersection type syntax in PHP

    PHP uses the ampersand (&) without spaces and escaped as & in HTML to declare intersection types.
  2. Step 2: Check each option

    function process(Countable&Iterator $obj) {} uses Countable&Iterator which is correct syntax for intersection types in PHP.
  3. Final Answer:

    function process(Countable&Iterator $obj) {} -> Option A
  4. Quick Check:

    Intersection uses & without spaces [OK]
Hint: Use & with no spaces for intersection types [OK]
Common Mistakes:
  • Using | instead of & for intersection
  • Adding spaces around &
  • Using comma instead of &
3. Given the following code, what will be the output?
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);
medium
A. foo bar
B. foo
C. bar
D. TypeError at runtime

Solution

  1. Step 1: Understand class C implements both interfaces

    Class C implements both A and B, so it has methods foo() and bar().
  2. 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.
  3. Final Answer:

    foo bar -> Option A
  4. Quick Check:

    Object meets both interfaces, so output is 'foo bar' [OK]
Hint: Check if object implements all interfaces in intersection [OK]
Common Mistakes:
  • Expecting only one method output
  • Thinking intersection causes error if both interfaces implemented
  • Confusing union with intersection types
4. What is the error in this code snippet?
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);
medium
A. No error, code runs fine.
B. TypeError because $z does not implement interface Y.
C. Syntax error in function declaration.
D. Fatal error: method y() not found in class Z.

Solution

  1. Step 1: Check class Z interfaces

    Class Z implements only interface X, not Y.
  2. Step 2: Analyze function parameter type

    Function example requires an object implementing both X and Y (intersection). Passing $z violates this.
  3. Final Answer:

    TypeError because $z does not implement interface Y. -> Option B
  4. Quick Check:

    Intersection requires all interfaces, missing one causes TypeError [OK]
Hint: All interfaces in intersection must be implemented [OK]
Common Mistakes:
  • Assuming partial interface implementation is enough
  • Confusing syntax error with type error
  • Thinking missing method causes fatal error instead of TypeError
5. You want to write a function that accepts an object which must be both 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+?
hard
A. function process(JsonSerializable|Countable $obj) { $obj->customMethod(); }
B. function process(JsonSerializable&Countable&CustomInterface $obj) {}
C. function process(object $obj) { $obj->customMethod(); }
D. function process(JsonSerializable&Countable $obj) { if (method_exists($obj, 'customMethod')) { $obj->customMethod(); } }

Solution

  1. Step 1: Understand intersection type usage

    Use & to require both JsonSerializable and Countable interfaces.
  2. Step 2: Handle custom method not in interfaces

    Since customMethod() is not part of these interfaces, check its existence with method_exists before calling.
  3. Final Answer:

    function process(JsonSerializable&Countable $obj) { if (method_exists($obj, 'customMethod')) { $obj->customMethod(); } } -> Option D
  4. Quick Check:

    Intersection + runtime check for extra method [OK]
Hint: Use & for interfaces and method_exists for extra methods [OK]
Common Mistakes:
  • Using union (|) instead of intersection (&)
  • Assuming method in interfaces without checking
  • Ignoring type safety by using object without interfaces
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard