0
0
PHPprogramming~30 mins

Intersection types in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Intersection Types in PHP
📖 Scenario: Imagine you are building a simple system to manage different types of workers in a company. Some workers can both write reports and attend meetings. You want to make sure that certain functions only accept workers who can do both tasks.
🎯 Goal: You will create interfaces for ReportWriter and MeetingAttendee, then create a class that implements both. Finally, you will write a function that accepts only objects that satisfy both interfaces using intersection types.
📋 What You'll Learn
Create two interfaces: ReportWriter and MeetingAttendee with one method each.
Create a class Employee that implements both interfaces.
Write a function handleWorker that accepts a parameter with an intersection type of ReportWriter&MeetingAttendee.
Call the function with an Employee object and print messages from both methods.
💡 Why This Matters
🌍 Real World
Intersection types help ensure that objects passed to functions meet multiple requirements, useful in complex systems where roles overlap.
💼 Career
Understanding intersection types is important for writing clear, type-safe code in PHP, especially in large projects or when using modern PHP features.
Progress0 / 4 steps
1
Create interfaces for report writing and meeting attendance
Create two interfaces called ReportWriter and MeetingAttendee. In ReportWriter, declare a public method writeReport(). In MeetingAttendee, declare a public method attendMeeting().
PHP
Need a hint?

Use the interface keyword to create interfaces. Each interface should have one method declaration without a body.

2
Create a class that implements both interfaces
Create a class called Employee that implements both ReportWriter and MeetingAttendee. Implement the methods writeReport() and attendMeeting() to return the strings "Report written." and "Meeting attended." respectively.
PHP
Need a hint?

Use implements keyword to implement multiple interfaces. Each method must return the exact string.

3
Write a function using intersection types
Write a function called handleWorker that accepts one parameter with the intersection type ReportWriter&MeetingAttendee. Inside the function, call writeReport() and attendMeeting() on the parameter and store their results in variables $report and $meeting.
PHP
Need a hint?

Use the intersection type ReportWriter&MeetingAttendee in the function parameter to require both interfaces.

4
Call the function and print the results
Inside the handleWorker function, add two echo statements to print $report and $meeting each followed by a newline. Then, create an Employee object called $employee and call handleWorker($employee).
PHP
Need a hint?

Use echo to print the strings with a newline character \n. Create the object and call the function after it.