0
0
PHPprogramming~5 mins

Nullable types in functions in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does a nullable type mean in PHP function parameters?
A nullable type means the function parameter can accept either the specified type or null. It is declared by adding a question mark ? before the type.
Click to reveal answer
beginner
How do you declare a nullable integer parameter in a PHP function?
You declare it by adding a question mark before the type like this: <code>function example(?int $number) { ... }</code>. This means <code>$number</code> can be an integer or <code>null</code>.
Click to reveal answer
intermediate
What happens if you pass null to a function parameter that is not nullable?
PHP will throw a TypeError because the parameter expects a specific type and null is not allowed unless the type is nullable.
Click to reveal answer
intermediate
Can return types in PHP functions be nullable? How?
Yes, return types can be nullable by adding a question mark before the return type. For example: <code>function getValue(): ?string { ... }</code> means the function returns a string or <code>null</code>.
Click to reveal answer
beginner
Why are nullable types useful in PHP functions?
Nullable types allow functions to explicitly accept or return null values, making the code clearer and safer by defining when null is an acceptable value.
Click to reveal answer
How do you declare a nullable string parameter in a PHP function?
Afunction example(string? $param) {}
Bfunction example(?string $param) {}
Cfunction example(string|null $param) {}
Dfunction example($param: ?string) {}
What will happen if you pass null to a non-nullable int parameter?
APHP will throw a TypeError.
BIt will work fine.
CThe parameter will be converted to 0.
DPHP will ignore the parameter.
Which of these is a valid nullable return type declaration?
Afunction foo(): array|null {}
Bfunction foo(): array? {}
Cfunction foo(): ?array {}
Dfunction foo(): nullable array {}
Nullable types were introduced in which PHP version?
APHP 5.6
BPHP 7.4
CPHP 8.0
DPHP 7.1
What does this function signature mean? function test(?float $value): ?float
AParameter and return value can be float or null.
BParameter must be float, return can be null.
CParameter can be null, return must be float.
DNeither parameter nor return can be null.
Explain how to declare a nullable parameter and a nullable return type in a PHP function.
Think about the question mark symbol and where it goes.
You got /4 concepts.
    Why is it important to use nullable types in PHP functions? Give an example scenario.
    Consider when a value might be missing or optional.
    You got /4 concepts.