Modern PHP types document contracts using scalar, nullable, union and object types.
What It Does
Modern PHP types document contracts using scalar, nullable, union and object 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 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
A value object adds a domain invariant beyond basic scalar declarations.
<?php
final readonly class EmailAddress { public function __construct(public string $value) { if (!filter_var($value, FILTER_VALIDATE_EMAIL)) throw new InvalidArgumentException('Bad email'); } }
function deliver(EmailAddress $to): string { return $to->value; }
echo deliver(new EmailAddress('[email protected]'));
Important Behavior and Edge Cases
Types cannot enforce business invariants such as owner matching or nonnegative balances.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Using Modern Type Declarations Instead of Loose Contracts | Modern PHP types document contracts using scalar, nullable, union and object types. |
| Related approach | Value objects and explicit validation protect domain constraints. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Using Modern Type Declarations Instead of Loose Contracts | Types cannot enforce business invariants such as owner matching or nonnegative balances. |
| Assuming a related mechanism has the same behavior | Value objects and explicit validation protect domain constraints. |
Key Takeaways
- Modern PHP types document contracts using scalar, nullable, union and object types.
- Types cannot enforce business invariants such as owner matching or nonnegative balances.
- Value objects and explicit validation protect domain constraints.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.