Strict Types and Type Declarations

6.Strict Types and Type Declarations

M

In this chapter

We'll learn what a type is, how a function can say which types it accepts and returns, how PHP quietly converts values when they don't match — and how one line, declare(strict_types=1), makes PHP stop with a clear error instead of guessing.

14–16 min

The Problem in Real Life

Tom adds a new service: a beard trim for £12.50. Mia uses the small function Marcus wrote for prices, totalPrice(), to work out the cost for two people. The page says £24.

Two beard trims at £12.50 should be £25. Where did the extra 50p go? Hidden at the very top of the log there's one line she almost missed: Deprecated: Implicit conversion from float 12.5 to int loses precision.

Marcus reads it and sighs. "The function said it wanted whole numbers. You gave it 12.50, and PHP quietly chopped off the .50 to make it fit — and carried on. Let's make PHP stop and tell us, instead of guessing."

M

PHP changed my price without asking — and only left a note in the log?

Mia

PHP Guessing vs. PHP Checking

A wrong total, no error

A price lost its pence and the page still loaded as if nothing happened.

PHP converts quietly

By default, PHP changes a value into the type a function expects, whenever it can.

One line to stop guessing

Strict mode makes PHP refuse the wrong type and say exactly where.

Strict Types and Type Declarations

Types: every value in PHP has a type — the kind of value it is. You'll study them properly in Act 04; for now, these four are enough:

  • int (integer): a whole number, like 25 or -3.
  • float: a number with a decimal point, like 12.5.
  • string: text, like "Tom's Barbershop" or "25" — yes, digits in quotes are text, not a number.
  • bool (boolean): true or false.

Functions, in one paragraph: to understand type declarations you need a quick look at functions (Act 09 teaches them fully). A function is a named, reusable piece of code. You give it some values to work with — its parameters, written in brackets — and it gives back a result with return. In the code below, totalPrice() takes a price and a number of people and gives back their product. You call (run) it by writing its name with values in brackets: totalPrice(25, 2).

A function with type declarations
<?php
function totalPrice(int $price, int $people): int
{
return $price * $people;
}
echo totalPrice(25, 2); // 50

int $price and int $people: the parameters must be ints. : int — the function gives back an int.

Type declarations: look at how that function is written: function totalPrice(int $price, int $people): int. The word int in front of each parameter is a type declaration: it says "this parameter must be an int". The : int after the brackets is a return type: it says "this function gives back an int". Type declarations are promises written into the code — for PHP, which checks them, and for every developer who reads the function later.

What PHP does when a type doesn't match — by default: without anything else, PHP runs in coercive mode: when a value has the wrong type, PHP tries to convert it. The code below shows what happens. The string "25" is quietly turned into the number 25 — handy. Text that isn't a number, like "twenty" or even "25 USD", can't be converted, so PHP stops with a TypeError (an error saying a value had the wrong type). And the dangerous case: the float 12.5 is turned into the int 12 — the .50 is simply thrown away, with only a "Deprecated" note in the log. That's exactly how Mia's beard trims lost 50p each.

Default (coercive) mode: PHP converts when it can
<?php
function totalPrice(int $price, int $people): int
{
return $price * $people;
}
echo totalPrice("25", 2); // 50 — "25" quietly became 25
echo totalPrice(12.5, 2); // 24 — 12.5 became 12!
// Deprecated: Implicit conversion from float 12.5 to int loses precision
echo totalPrice("twenty", 2);
// Fatal error: Uncaught TypeError: totalPrice(): Argument #1 ($price)
// must be of type int, string given

Strict mode: you can switch the guessing off. Put declare(strict_types=1); at the top of a file, and calls made from that file use strict mode: a value must already have the declared type, or PHP stops with a TypeError right away. In the code below, totalPrice("25", 2) is no longer converted — it fails, and the message says exactly what went wrong: Argument #1 ($price) must be of type int, string given. It sounds harsher, but it's kinder: a loud error the moment you write the bug is much better than a wrong price that a customer finds weeks later.

Strict mode: no guessing
<?php
declare(strict_types=1);
function totalPrice(int $price, int $people): int
{
return $price * $people;
}
echo totalPrice(25, 2), "\n"; // 50
echo totalPrice("25", 2);
// Fatal error: Uncaught TypeError: totalPrice(): Argument #1 ($price)
// must be of type int, string given, called in main.php on line 11

The rules of the declare line: declare(strict_types=1); must be the very first statement in the file — straight after <?php, before anything else. If any other statement comes first, PHP refuses to run the file at all, as the code below shows. It applies to the file it's written in: calls made from that file are checked strictly. That's why the habit at BookBay — and in most modern PHP projects — is simple: every PHP file starts with the strict types line, declare(strict_types=1);. Act 03 onwards, every example in this course does.

The declare line must come first
<?php
echo "Booking page\n";
declare(strict_types=1);
// Fatal error: strict_types declaration must be the very first statement in the script

Return types are checked too: the same rule applies to what a function gives back. Below, slotLabel() promises to return a string but returns the int 9. Without strict mode, PHP converts it to the text "9". With strict mode, PHP stops: "Return value must be of type string, int returned" — pointing straight at the function that broke its promise.

Return types are checked too
<?php
declare(strict_types=1);
function slotLabel(int $hour): string
{
return $hour; // returns an int, but promised a string
}
var_dump(slotLabel(9));
// Fatal error: Uncaught TypeError: slotLabel(): Return value must be of type string, int returned

Without the declare line, PHP would convert 9 to "9" and carry on.

One sensible exception: even in strict mode, an int is accepted where a float is expected — every whole number is also a valid decimal number, and nothing is lost. So averagePrice(100, 4) works fine with a float $total parameter. The table below sums up what happens to each kind of value, with and without strict mode.

Table — What happens to each value, with and without strict mode
Value passed to an int parameterDefault (coercive) modeStrict mode
25 (int)Works: 25Works: 25
"25" (string)Converted to 25TypeError
12.5 (float)Converted to 12 — .50 lost, only a Deprecated noteTypeError
"25 USD" (string)TypeErrorTypeError
"twenty" (string)TypeErrorTypeError
100 (int), but to a float parameterWorks: 100.0Works: 100.0
An int is fine where a float is expected
<?php
declare(strict_types=1);
function averagePrice(float $total, int $bookings): float
{
return $total / $bookings;
}
echo averagePrice(100, 4); // 25 — the int 100 is accepted as 100.0

Key Takeaway

A type declaration says what type a function's parameters and return value must be. By default PHP converts values that don't match — sometimes losing data silently. declare(strict_types=1) as the very first statement turns that guessing into an immediate TypeError, so wrong types are caught where they happen. Start every PHP file with it.

Why This Matters

Prices, times and counts are the heart of BookBay's booking product, and a value that is quietly converted is how money goes missing without anyone noticing. Strict types turn those silent mistakes into loud, precise errors while Mia is still writing the code — long before Tom's customers ever see a wrong total.

Type declarations also make code easier to read: totalPrice(int $price, int $people): int tells you what goes in and what comes out without reading a single line of the function. Tools you'll meet later, like PHPStan (Act 21), use them to find bugs before the code even runs.

Mia adds declare(strict_types=1); to the top of the file and runs it again. Now the error appears at once, pointing straight at the line that passed 12.5. To understand what was really in her variables, Marcus shows her one last tool: a way to look inside any value. That's the next chapter.