Type declarations specify what type a function expects and returns: int, string, bool, or a class name. Adding declare(strict_types=1) enforces these strictly. Type hints catch bugs early and make code self-documenting.
Type Declarations (PHP 7+)
// Parameter types
function add(int $a, int $b): int {
return $a + $b;
}
// Nullable types
function find(?int $id): ?string {
return $id ? "found" : null;
}
// Union types (PHP 8)
function process(int|string $input): void {}
// Return types
function getData(): array { return []; }
function getName(): string { return "Alice"; }
function doSomething(): void { /* no return */ }
function alwaysFails(): never { throw new Exception(); }
// Typed properties (PHP 7.4+)
class User {
public int $id;
public string $name;
public ?string $email = null;
public array $roles = [];
}
// strict_types
declare(strict_types=1); // must be first line