0
0
PHPprogramming~5 mins

Union types in practice in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
Afunction foo(int|string& $param) {}
Bfunction foo(int&string $param) {}
Cfunction foo(int|string $param) {}
Dfunction foo(int|string, $param) {}
What will happen if you pass a float to a parameter declared as int|string?
AIt will be accepted without error.
BPHP will throw a TypeError at runtime.
CPHP will convert the float to int automatically.
DThe function will return null.
How do you include null as an allowed type in a union type?
AUse <code>int|string|null</code>
BUse <code>int|string?null</code>
CUse <code>int|string|void</code>
DUse <code>int|string|nullable</code>
Can union types be used for return types in PHP?
AOnly for class types.
BNo, union types only work for parameters.
COnly for void return types.
DYes, you can declare multiple return types using union types.
Which PHP version introduced union types?
APHP 8.0
BPHP 8.1
CPHP 7.4
DPHP 8.2
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.