← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 14 of 24

PHP Type Declarations

Scalar Type Declarations

Adding a type before a function parameter (like function greet(string $name)) makes PHP reject calls with the wrong argument type, catching bugs at the call site instead of deep inside the function body.

Example: Scalar Type Declarations

php
<?php
function greet(string $name) {
    echo "Hello, $name!";
}
greet("Alice");
?>

Return Type Declarations

A return type declared after the parameter list (function getAge(): int) documents and enforces what a function promises to hand back, which helps both readers and static analysis tools trust the function's contract.

Example: Return Type Declarations

php
<?php
function getAge(): int {
    return 30;
}
echo getAge();
?>

Nullable Types

Prefixing a type with a question mark (?string) allows either that type or null, which is essential for parameters or return values that genuinely might have no value, like an optional lookup that can fail to find anything.

Example: Nullable Types

php
<?php
function findUser(?string $name): ?string {
    return $name;
}
var_dump(findUser(null));
?>

Strict Types

declare(strict_types=1) at the top of a file disables PHP's usual implicit type coercion for that file, so passing a string where an int is expected throws a TypeError instead of silently converting.

Example: Strict Types

php
<?php
declare(strict_types=1);

function double(int $x): int {
    return $x * 2;
}
echo double(5);
// double("5") would now throw a TypeError instead of silently converting
?>

Iterable Type

The iterable type accepts either a plain array or any object implementing Traversable, letting a function accept 'anything you can foreach over' without caring which concrete form it takes.

Example: Iterable Type

php
<?php
function printAll(iterable $items) {
    foreach ($items as $item) {
        echo $item . "\n";
    }
}
printAll([1, 2, 3]);
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.