Return type declarations constrain the values returned by functions and methods.
What It Does
Return type declarations constrain the values returned by functions and methods. 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 total(int $quantity, float $price): float { return $quantity * $price; }
echo total(3, 4.5);
Example 2: Another Case
Examine the edge case and the observable result.
<?php
function findName(int $id): ?string { return $id === 5 ? 'Rita' : null; }
var_dump(findName(8));
Practical Example: Putting It to Use
Apply the technique to a small practical task.
<?php
final class Price { public function __construct(public readonly int $cents) {} }
function formatPrice(Price $price): string { return number_format($price->cents / 100, 2); }
echo formatPrice(new Price(1250));
Important Behavior and Edge Cases
A function declared void must not return a value, and never must not finish normally.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Return Types | Return type declarations constrain the values returned by functions and methods. |
| Related approach | Nullable or union return types can express valid alternative outcomes. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Return Types | A function declared void must not return a value, and never must not finish normally. |
| Assuming a related mechanism has the same behavior | Nullable or union return types can express valid alternative outcomes. |
Key Takeaways
- Return type declarations constrain the values returned by functions and methods.
- A function declared void must not return a value, and never must not finish normally.
- Nullable or union return types can express valid alternative outcomes.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.