📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Type Declarations

Type Declarations

5 min read Quiz at the end
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
Topic Quiz · 5 questions

Test your understanding before moving on

1. What does declare(strict_types=1) do?
💡 strict_types=1 makes PHP throw TypeErrors instead of quietly coercing types.
2. What is a nullable type?
💡 ?string means the value can be a string OR null.
3. What does void return type mean?
💡 void means the function should not return a value (technically returns null).
4. Which is a valid union type (PHP 8)?
💡 Union types use the pipe: int|string means either an int or a string.
5. What does the never return type mean?
💡 never means the function always throws an exception or calls exit().