Recall & Review
beginner
What is a union type in PHP?
A union type allows a function or method to accept multiple different types for a parameter or return value, separated by a pipe (|). For example,
int|string means the value can be either an integer or a string.Click to reveal answer
beginner
How do you declare a function parameter that accepts either an int or a string in PHP?
You declare it using a union type like this: <code>function example(int|string $param) { ... }</code>. This means <code>$param</code> can be an integer or a string.Click to reveal answer
intermediate
Can union types include null in PHP? How?
Yes, you can include
null in union types by adding it explicitly, for example: int|string|null. This means the value can be an integer, a string, or null.Click to reveal answer
intermediate
What happens if a value passed to a union typed parameter does not match any of the allowed types?
PHP will throw a TypeError at runtime, indicating the value does not match the declared union types.
Click to reveal answer
beginner
Show an example of a function with a union return type in PHP.
Example:<br><code>function getId(): int|string {<br> return rand(0,1) ? 123 : 'abc';<br>}</code><br>This function returns either an integer or a string.Click to reveal answer
Which of the following is a valid union type declaration for a parameter that accepts int or string?
✗ Incorrect
Union types use the pipe (|) symbol between types, so
int|string is correct.What will happen if you pass a float to a parameter declared as
int|string?✗ Incorrect
Only int or string are allowed. Passing a float causes a TypeError.
How do you include null as an allowed type in a union type?
✗ Incorrect
You explicitly add
null to the union types.Can union types be used for return types in PHP?
✗ Incorrect
Union types can be used for both parameters and return types.
Which PHP version introduced union types?
✗ Incorrect
Union types were introduced in PHP 8.0.
Explain what union types are and how you use them in PHP function parameters.
Think about allowing more than one type for a parameter.
You got /3 concepts.
Describe how PHP handles a value passed to a union typed parameter that does not match any allowed type.
What happens if the type is wrong?
You got /3 concepts.