← 返回课程: PHP from scratch

Type declarations, strict_types and week 2 review

视频即将上线

In the previous lessons you saw that PHP converts types automatically. That is convenient for small scripts, but in a large program it creates silent bugs: a function expects a number, receives the text 'abc' and works with a wrong value without warning. Modern PHP lets you declare the types of parameters and return values, and turn on a strict mode that converts those slips into clear errors. It is one of the best habits you can acquire from day one.

Types on parameters and return values

Although functions are studied in depth in week 4, we need the basic form: the function keyword, a name, the parameters with their type and, after a colon, the type it returns. Available types are int, float, string, bool, array, object, and class names. If a function returns nothing, its type is void. A type preceded by a question mark accepts null (nullable), and with the vertical bar you declare a union, for example int|string.

php
<?php

declare(strict_types=1);

function add(int $a, int $b): int
{
    return $a + $b;
}

function greet(string $name, ?string $title = null): string
{
    return $title === null ? "Hello, $name" : "Hello, $title $name";
}

function show(int|string $id): void
{
    echo 'ID: ', $id, "\n";
}

echo add(2, 3), "\n";                 // 5
echo greet('Ana'), "\n";              // Hello, Ana
echo greet('Ana', 'Dr.'), "\n";       // Hello, Dr. Ana
show(10);
show('A-77');

What declare(strict_types=1) does

Without strict mode, PHP tries to convert arguments to the declared type: passing the text '5' to an int parameter works, and passing 5.7 converts it to 5 with a deprecation notice. With declare(strict_types=1) as the first statement of the file, any type different from the declared one throws a TypeError. The only conversion kept is from int to float, because it loses no information. Strict mode applies to calls made from that file, so put it at the top of all your files.

php
<?php

declare(strict_types=1);

function twice(int $n): int
{
    return $n * 2;
}

echo twice(21), "\n";          // 42

try {
    echo twice('21'), "\n";    // TypeError in strict mode
} catch (TypeError $e) {
    echo 'Error: ', $e->getMessage(), "\n";
}

function average(float ...$values): float
{
    return array_sum($values) / count($values);
}
echo average(1, 2, 4), "\n";    // 2.3333333333333 (int to float is allowed)

Notice the try and catch block: it catches the TypeError and shows its message instead of stopping the program. We will study it in depth in week 8; for now it is enough to know it reacts to errors. You will also see the three-dots syntax before a parameter, which gathers a variable number of arguments into an array.

When types help

Types work as documentation that PHP checks for you. Your editor uses them to autocomplete and warn about errors before running. They make a failure show up where it happens and not three functions later. A tip: add types gradually, start with new functions, and avoid the mixed type unless it is unavoidable. With form data, which always arrives as text, convert first (for example with (int)) and then pass the value to the function.

检验所学

第 1 / 7

What does mb_strlen('canción') return?

✎ 我的笔记

仅保存在此浏览器中。登录后可保存到账号。0/5000 字符

← 上一节下一节 →