Content · Web Development · PHP

Using Modern PHP Type Declarations Instead of Loose Contracts

Modern PHP types document contracts using scalar, nullable, union and object types. Types cannot enforce business invariants such as owner matching or nonnegative.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 admin

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


OptionWhat it means in practice
Using Modern Type Declarations Instead of Loose ContractsModern PHP types document contracts using scalar, nullable, union and object types.
Related approachValue objects and explicit validation protect domain constraints.

Common Beginner Mistakes


MistakeCorrect approach
Ignoring the important boundary for Using Modern Type Declarations Instead of Loose ContractsTypes cannot enforce business invariants such as owner matching or nonnegative balances.
Assuming a related mechanism has the same behaviorValue 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.

Share this resourceSend this page to someone who may find it useful.