Nullable and union types express optional results and several accepted value types.
What It Does
Nullable and union types express optional results and several accepted value types. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Start with the smallest meaningful working case.
<?php
function nick(?string $name): string { return $name ?? 'Visitor'; }
echo nick(null);
Example 2: Another Case
Examine the edge case and the observable result.
<?php
function lookup(int $id): ?array { return $id === 1 ? ['id' => 1] : null; }
var_dump(lookup(2));
Practical Example: Putting It to Use
Combine a union-typed parameter with a nullable return contract.
<?php
function lookupCode(int|string|null $code): ?string { return $code === null ? null : strtoupper((string) $code); }
var_dump(lookupCode('a4'), lookupCode(null));
Important Behavior and Edge Cases
A nullable type is a union with null, but absence of a required argument is still an error.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Nullable and Union Types | Nullable and union types express optional results and several accepted value types. |
| Related approach | Use ?T for simple nullable types and T or null for larger unions. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Nullable and Union Types | A nullable type is a union with null, but absence of a required argument is still an error. |
| Assuming a related mechanism has the same behavior | Use ?T for simple nullable types and T or null for larger unions. |
Key Takeaways
- Nullable and union types express optional results and several accepted value types.
- A nullable type is a union with null, but absence of a required argument is still an error.
- Use ?T for simple nullable types and T or null for larger unions.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.