×

php · level 2 · unit 7 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Type declarations say what goes in and what comes out.

Write a type before a parameter and PHP checks every value that arrives: function area(int $width, int $height). That is a . The common types are int, float, string, bool and array.

A goes after the brackets, with a colon: function area(...): int. PHP then checks the answer too. means the function hands nothing back. Send the wrong kind of value and PHP stops with a that names the function and the argument.

Number-like strings are still converted, so area("2", 5) works. area("two", 5) does not.

<?php
function area(int $width, int $height): int {
    return $width * $height;
}
function show(string $room, int $size): void {
    echo "$room: $size square metres\n";
}
show("Kitchen", area(3, 4));
show("Hall", area("2", 5));

Types also work as notes for people reading your code, telling them what each function expects.