0
0
PHPprogramming~30 mins

Intersection types in practice in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Intersection types in practice
📖 Scenario: Imagine you are building a simple system to manage different types of workers in a company. Some workers can both code and design. You want to make sure that certain functions only accept workers who can do both tasks.
🎯 Goal: You will create interfaces for coding and designing, then create a class that implements both. Finally, you will write a function that accepts only workers who are both coders and designers using intersection types.
📋 What You'll Learn
Create two interfaces: Coder and Designer
Create a class FullStackWorker that implements both Coder and Designer
Write a function workOnProject that accepts a parameter with an intersection type of Coder&Designer
Call the workOnProject function with an instance of FullStackWorker and print the result
💡 Why This Matters
🌍 Real World
Intersection types help ensure that objects passed to functions have multiple capabilities, useful in systems where roles overlap, like full-stack developers who code and design.
💼 Career
Understanding intersection types is important for writing clear, type-safe code in modern PHP applications, improving code quality and reducing bugs.
Progress0 / 4 steps
1
Create interfaces for coding and designing
Create two interfaces called Coder and Designer. Each interface should have one public method: code() for Coder and design() for Designer. Both methods should return a string.
PHP
Need a hint?

Use the interface keyword to create interfaces. Define methods with public visibility and specify the return type string.

2
Create a class that implements both interfaces
Create a class called FullStackWorker that implements both Coder and Designer interfaces. Implement the code() method to return the string 'Coding...' and the design() method to return the string 'Designing...'.
PHP
Need a hint?

Use implements keyword to implement multiple interfaces. Define both methods exactly as in the interfaces.

3
Write a function using intersection types
Write a function called workOnProject that accepts one parameter called worker with the intersection type Coder&Designer. Inside the function, return the concatenation of $worker->code() and $worker->design() separated by a space.
PHP
Need a hint?

Use the intersection type Coder&Designer in the function parameter to require both interfaces.

4
Call the function and print the result
Create an instance of FullStackWorker called worker. Call the function workOnProject with worker as argument and print the returned string.
PHP
Need a hint?

Create the object with new FullStackWorker() and use print() to show the result.