Union types in practice
📖 Scenario: You are building a simple PHP program to handle user input that can be either a string or an integer. This is common when dealing with form data where users might enter numbers or text.
🎯 Goal: Create a PHP function that accepts a parameter which can be either an int or a string using union types. The function will return a message describing the type and value of the input.
📋 What You'll Learn
Create a function called
describeInput that accepts a parameter with a union type int|string.Inside the function, use
is_int() and is_string() to check the type of the input.Return a string message describing the input type and value.
Call the function with both an integer and a string and print the results.
💡 Why This Matters
🌍 Real World
Handling user input that can be multiple types is common in web forms and APIs. Union types help make your code clear and safe.
💼 Career
Understanding union types is important for writing modern PHP code that is robust and easy to maintain, a skill valued in backend development jobs.
Progress0 / 4 steps