Scalar types

int in a signature is a promise, not decoration.

The scalar types in a signature are int, float, string and bool. function clamp(int $n, int $lo, int $hi): int tells the caller that a number came in. Without strict_types, PHP will try to convert the string "3" to an int. With the directive declare(strict_types=1) at the top of the file, such a string becomes a TypeError.

TypeError is an exception. You can catch it at the boundary and turn it into a 400. There is no need to silence it inside every function: then the signature lies. Let it fall through to the layer responsible for input.

The return type is checked too. You promised int and returned a string: another TypeError in strict mode. In weak mode PHP will try to convert. Do not mix modes in one project: the directive applies per file, and a library keeps its own.

In this lesson's task you can skip the types; the fork on the sign is what matters. But in service code an int signature on an identifier is cheaper than a comment saying "numbers only here". Nobody checks a comment.

Practice

  1. What strict_types does

    The file starts with declare(strict_types=1). What changes for an int argument?

    • All functions get faster
    • A foreign type is not converted silently
    • int turns into string
    • Autoloading is switched off
  2. The name of the type error

    What exception type does PHP throw on a type mismatch in strict mode? One word.

  3. The sign

    Write function sign($n). Return plus for a positive number, minus for a negative one and zero for zero.