0
0
PHPprogramming~5 mins

Union types 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 variable or parameter to accept values of multiple specified types. It is written using the pipe symbol (|) between types.
Click to reveal answer
beginner
How do you declare a function parameter that accepts either an int or a string using union types?
You declare it like this: <code>function example(int|string $param) { }</code>. This means $param can be an int or a string.
Click to reveal answer
intermediate
Can union types include null in PHP? How?
Yes. You can include null in a union type like int|null. This means the value can be an int or null.
Click to reveal answer
intermediate
What happens if a value passed to a union typed parameter does not match any of the types?
PHP will throw a TypeError at runtime because the value does not match the declared union types.
Click to reveal answer
advanced
Can you use union types with class types in PHP?
Yes. You can declare a parameter or property to accept multiple class types like <code>ClassA|ClassB</code>. The value must be an instance of either class.
Click to reveal answer
Which symbol is used to declare union types in PHP?
A:
B&
C,
D|
What will happen if you pass a float to a parameter declared as int|string?
AIt will accept the float without error.
BIt will throw a TypeError.
CIt will convert the float to int automatically.
DIt will ignore the parameter.
Can union types include the type 'null'?
AYes, by including null in the union.
BNo, null cannot be part of union types.
COnly if the type is nullable with ?.
DOnly for class types.
Which PHP version introduced union types?
APHP 8.0
BPHP 7.4
CPHP 8.1
DPHP 7.2
Is this a valid union type declaration? function test(int|float|string $value) {}
ANo, float cannot be in union types.
BNo, only two types allowed in union.
CYes, it accepts int, float, or string.
DYes, but only in PHP 7.
Explain what union types are in PHP and how to use them in function parameters.
Think about allowing multiple types for one variable.
You got /3 concepts.
    Describe what happens if a value does not match any type in a union type declaration.
    Consider PHP's behavior when types don't match.
    You got /3 concepts.