Introduction
Nullable types let a function accept either a specific type or null. This helps when a value might be missing or optional.
Nullable types let a function accept either a specific type or null. This helps when a value might be missing or optional.
function functionName(?TypeName $param): ?ReturnType { // function body }
The ? before a type means it can be that type or null.
You can use nullable types for both parameters and return values.
<?php function greet(?string $name): void { if ($name === null) { echo "Hello, guest!\n"; } else { echo "Hello, $name!\n"; } }
<?php function findUser(int $id): ?string { if ($id === 1) { return "Alice"; } return null; }
This program shows how a function uses a nullable integer parameter to describe age or say it's unknown.
<?php function describeAge(?int $age): string { if ($age === null) { return "Age is unknown."; } return "Age is $age years."; } echo describeAge(25) . "\n"; echo describeAge(null) . "\n";
Nullable types help avoid errors when values might be missing.
Remember to check for null inside the function before using the value.
Nullable types allow null or a specific type in functions.
Use ? before the type to make it nullable.
Check for null inside your function to handle missing values safely.
?int mean in a PHP function parameter?? before int means the parameter can accept null or an int value.null.? before the type, like ?string.?string correctly. function greet(string|null $name) {} uses union type syntax which is valid in PHP 8+, but the question asks for nullable syntax specifically. Options C and D are invalid syntax.function checkAge(?int $age) {
if ($age === null) {
return "Age not provided";
}
return "Age is $age";
}
echo checkAge(null);?int, so null is allowed. It checks if $age === null and returns "Age not provided".checkAge(null) triggers the null check, so it returns "Age not provided".function setName(?string name) {
echo $name;
}$. The parameter name is missing $.?string are valid. The function does not require a return value. Parameters can be nullable without default values.?float and returns float. It must handle null safely and return a float.$num is null. function square(?float $num): float {
if ($num === null) {
return 0;
}
return $num ** 2;
} checks for null explicitly and returns 0, then squares the number correctly. function square(float $num = null): float {
return $num * $num;
} uses default null but parameter is not nullable, causing a type error. function square(?float $num): ?float {
return $num ? $num * $num : 0;
} returns nullable float but uses a loose check $num ? which fails for 0.0 (falsey), so it returns 0 incorrectly.Pass the test and this pattern moves unknown