Thuta Learning
PHP
IntermediateProgrammingBeginner

Type Declarations & Strict Types

PHPLesson 1525 min

What you'll walk away with

  • Predict how an int parameter treats "5", true, 5.0 and "abc" in the default (weak) mode
  • Place declare(strict_types=1) as the first statement of a file and catch the resulting TypeError
  • Explain that strict mode depends on the file where the call is written
  • Understand that strict types are not validation, and convert and check form input at the boundary

Explain it simply

Explain it simply

A type declaration tells a function in advance: "I need an integer here" or "I will give you back a string". By default PHP is patient: if the string "5" arrives where an integer is expected, PHP quietly turns it into 5. That feels convenient, but it can also hide mistakes.

Writing declare(strict_types=1); at the top of a file makes the function calls inside that file stricter. Sending "5" to a function that wants an integer then stops being converted and throws a TypeError instead. This lesson looks closely at which file controls what, and when.

Problem → Why → Solution

The problem: PHP quietly accepts values you never meant to allow

A shopping cart function asks for int $qty. In a file that is not strict, addToCart(true) becomes 1, addToCart(2.9) becomes 2 (the fraction is lost), and addToCart("1e2") puts 100 items in the cart. No error stops any of them; only 2.9 produces a Deprecated: Implicit conversion from float 2.9 to int loses precision notice.

Data from a form always arrives as strings, so converting "3" is genuinely useful. But once PHP also accepts true, 2.9 and "1e2", the promise your code makes becomes blurry, and the bugs show up later, far from their cause.

weak-mode.php
<?php
// No declare(strict_types=1): PHP converts whatever it can
function addToCart(int $qty): string
{
    return "added $qty";
}

echo addToCart(true), "\n";    // added 1
echo addToCart(2.9), "\n";     // added 2   (Deprecated notice, fraction lost)
echo addToCart("1e2"), "\n";   // added 100

Why does PHP accept these?

PHP was built as a very forgiving language, so its default mode (coercive, or weak, mode) converts whatever scalars it can. That behaviour keeps old code working. Strict mode is opt-in, one file at a time, so you can write new code strictly and leave older code untouched.

Core concept: strict mode follows the file that makes the call

PHP has four scalar types (int, float, string, bool), and its other declarations cover array, object, callable, nullable types such as ?int, union types such as int|string (since PHP 8.0) and intersection types such as A&B (since PHP 8.1). Non-scalar declarations like classes, arrays and callables are always enforced strictly; strict_types affects scalars only. In the default mode PHP converts every scalar it can and throws a TypeError only for the rest. A TypeError is a catchable exception whose message names the function, the argument, the type it expected and the type it received.

When declare(strict_types=1); is the first statement of a file, calls made from that file accept exact types only. The single exception is that an int may be passed where a float is expected, because widening an int to a float loses no information. Sending "5" for an int, 5 for a string or 5.0 for an int is a TypeError. A function's return value is checked as well, using the setting of the file that declares the function.

The most important point is that strict_types is caller-sensitive. The file that declares the function does not decide how its arguments are checked; the file that writes the call does. So a non-strict file that sends "21" to a strict library function still gets it converted and working. Calls made by PHP's own functions, such as array_map calling your callback, also stay in weak mode even when written inside a strict file. Finally, strict types are not validation: int $age happily accepts -5, so the allowed range is still yours to check.

Mental model: look at the file that writes the call
  1. Call is written in some file
  2. PHP reads that file's strict flag
  3. Strict: exact type, int may widen
  4. Weak: compatible values converted

Return types are the exception: they follow the file that declares the function, so arguments and returns can follow different files.

General pattern

php
<?php
declare(strict_types=1);   // first statement; applies to this file only

function name(int $a, ?string $b, int|float $c): ReturnType
{
    return $value;   // checked against ReturnType
}
try {
    name($x, $y, $z);
} catch (TypeError $e) {
    // a wrong scalar type reached a parameter or a return
}

The declare must be the first statement of the file (only comments may come before it). It is written per file and does not spread to other files you include. A TypeError can be caught with try/catch.

Example: a total() function in a strict file

This script shows four calls in strict mode: a normal call, an int passed to a float, a string that causes a TypeError, and finally a call with the right types but a bad value, which triggers an exception we wrote ourselves. A TypeError message normally ends with ", called in /path/file.php on line N", so strstr() cuts that part off to keep the output readable.

strict.php
<?php
declare(strict_types=1);

function total(int $qty, float $price): float
{
    if ($qty < 0 || $price < 0) {
        throw new InvalidArgumentException('positive values required');
    }
    return $qty * $price;
}

echo total(3, 19.5), "\n";
echo total(2, 10), "\n";

try {
    echo total("3", 19.5), "\n";
} catch (TypeError $e) {
    echo "TypeError: ", strstr($e->getMessage(), ', called in', true), "\n";
}

try {
    echo total(-1, 5), "\n";
} catch (InvalidArgumentException $e) {
    echo "Invalid: ", $e->getMessage(), "\n";
}

Code breakdown

  1. The declarationdeclare(strict_types=1);

    This must be the first statement of the file. Because it is there, every call below is checked for exact scalar types.

  2. The signaturefunction total(int $qty, float $price): float

    Both parameters and the return are typed. In strict mode $qty must be a real int and $price a float (or an int, which widens).

  3. The guardthrow new InvalidArgumentException('positive values required');

    A type check cannot catch a value that is the right type but wrong (-1), so the function checks it itself and throws. Strict types do not replace validation.

  4. int widens to floatecho total(2, 10), "\n";

    10 is an int, but $price is a float, so even strict mode accepts it. This is the only conversion allowed, and the result is 20.

  5. Catching TypeErrorecho "TypeError: ", strstr($e->getMessage(), ', called in', true), "\n";

    "3" is a string, so a TypeError is thrown. The true flag of strstr() keeps only the text before ', called in', which gives a message without a file path.

You should see
58.5
20
TypeError: total(): Argument #1 ($qty) must be of type int, string given
Invalid: positive values required

What weak mode converts

In a file without strict_types, an int parameter accepts many convertible values. The script below sends a variety of values to one function and shows what happens. Deprecated notices are caught with set_error_handler() and printed alongside, so the output does not depend on your php.ini.

coercion.php
<?php
$notes = [];
set_error_handler(function (int $level, string $message) use (&$notes): bool {
    $notes[] = $message;
    return true;
});

function describe(int $n): string
{
    return "int($n)";
}

$inputs = ["5", "5.0", " 5", "1e2", true, 5.0, 5.5, "5 apples", "abc", null];
foreach ($inputs as $value) {
    $notes = [];
    try {
        $result = describe($value);
    } catch (TypeError $e) {
        $result = "TypeError";
    }
    echo str_pad(var_export($value, true), 11), " => ", $result;
    if ($notes) {
        echo "   [", $notes[0], "]";
    }
    echo "\n";
}

The results show that "5", "5.0", " 5", "1e2", true and 5.0 all become an int (1e2 is 100, true is 1). 5.5 is cut to 5 with the Deprecated notice Implicit conversion from float 5.5 to int loses precision; that is the behaviour of the PHP 8.3 used for this lesson, and deprecated behaviour can change in later versions. "5 apples", "abc" and null are TypeErrors, so even weak mode does not accept everything.

Built-in functions and callbacks inside a strict file

Even PHP's built-in functions are strict when called from a strict file: strlen(123) gives a TypeError. But in array_map($double, ["1", "2"]) the caller of $double is array_map itself, not your code, so it runs in weak mode and "1" becomes 1. Return types are strict too: five(): int returning 5.0 is a TypeError, because a float is no longer accepted as an int.

strict-edges.php
<?php
declare(strict_types=1);

function attempt(string $label, callable $fn): void
{
    try {
        $result = $fn();
    } catch (TypeError $e) {
        $message = strstr($e->getMessage(), ', called in', true) ?: $e->getMessage();
        $result = "TypeError: " . $message;
    }
    echo $label, ": ", $result, "\n";
}

$double = fn(int $n): int => $n * 2;
attempt("direct call", fn() => $double("21"));
attempt("array_map callback", fn() => implode(",", array_map($double, ["1", "2"])));
attempt("built-in strlen(123)", fn() => strlen(123));

function half(float $n): float { return $n / 2; }
attempt("int into float", fn() => half(5));

function five(): int { return 5.0; }
attempt("float returned as int", fn() => five());

The output: direct call is a TypeError, the array_map callback gives 2,4, built-in strlen(123) is a TypeError, int into float gives 2.5, and float returned as int is a TypeError. If you need strict checks inside a callback, add checks such as is_int() in the callback itself, or call it from your own foreach instead of array_map.

Which file calls: a two-file demonstration

To confirm that the rule is caller-sensitive, the script below creates four files in a temp folder and includes them. strict_lib.php holds two strict functions and loose_lib.php holds one non-strict function. Then one non-strict caller and one strict caller each call one of them.

two-files.php
<?php
$dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . "strict_demo_" . getmypid();
mkdir($dir);

file_put_contents($dir . "/strict_lib.php", '<?php
declare(strict_types=1);
function twice(int $n): int { return $n * 2; }
function sloppy(): int { return "7"; }
');
file_put_contents($dir . "/loose_lib.php", '<?php
function triple(int $n): int { return $n * 3; }
');
file_put_contents($dir . "/loose_caller.php", '<?php
require __DIR__ . "/strict_lib.php";
echo twice("21"), "\n";
try {
    echo sloppy(), "\n";
} catch (TypeError $e) {
    echo "TypeError: ", $e->getMessage(), "\n";
}
');
file_put_contents($dir . "/strict_caller.php", '<?php
declare(strict_types=1);
require __DIR__ . "/loose_lib.php";
try { echo triple("5"), "\n"; } catch (TypeError $e) {
    echo "TypeError: ", strstr($e->getMessage(), ", called in", true), "\n";
}
');

echo "non-strict caller, strict library:\n";
include $dir . "/loose_caller.php";
echo "strict caller, non-strict library:\n";
include $dir . "/strict_caller.php";

array_map("unlink", glob($dir . "/*.php"));
rmdir($dir);

In the first run, twice("21") in the strict library returns 42, because the calling file is not strict and "21" is converted. But sloppy(): int returns "7" and raises a TypeError, because return values are checked with the file that declares the function (strict). In the second run the strict caller calls the non-strict function triple("5") and gets a TypeError. To know what applies, look at the calling file, not just the library's own declare.

A quick map of type declarations

TypeSinceMeaning
?int7.1an int or null
void7.1no return value
int|string8.0union: either listed type
mixed8.0any value at all
A&B8.1intersection: both class types at once
never8.1the function never returns (exit or throw)

When choosing among these, treat a broad type such as mixed as a last resort: the more precise the promise, the more a reader can trust the code. ?int and int|null mean the same thing, and ?int is just shorter.

In real projects

Where this shows up in real projects

Many modern PHP codebases make declare(strict_types=1); a house rule at the top of every file, often enforced by a linter or coding-standard tool. The payoff is that type mistakes surface while you write code or run tests, not in production. Static analysis tools also give more useful answers on code that uses strict types.

The main challenge in a strict file is converting input at the boundary. Values from $_GET, $_POST and $_COOKIE are strings (or arrays), so they cannot go straight into a function that wants an int. Convert and validate with something like filter_var($raw, FILTER_VALIDATE_INT), then pass the result on. Some database drivers return numbers as strings (depending on driver and settings), so the same boundary rule applies there. json_decode, on the other hand, yields ints, floats and strings with their proper types.

Common mistakes

Common mistakes

1. Believing a declare in the library also protects it from sloppy callers

Adding strict_types=1 to the file that declares a function, but not to the file that calls it, still lets the caller's arguments be converted (only the function's own return value is checked strictly). To really enforce arguments, put the declare in every file that makes calls, or check inside the function yourself with something like is_int().

2. Putting declare anywhere but the first statement

Writing an echo after <?php and only then declare(strict_types=1); gives Fatal error: strict_types declaration must be the very first statement in the script. HTML before <?php is just as bad. Only comments may precede the declare.

3. Removing strict mode to silence TypeErrors from form strings

When $_POST['qty'] is the string "3" and a TypeError appears, deleting the declare only hides the problem. The real issue is passing unconverted, unchecked input, so convert it at the boundary with filter_var() and call the function only when it is valid.

4. Assuming a correct type means a correct value

Passing -5 or 9999 to function setAge(int $age) is accepted because the type is right. Strict types check only whether the value is an int, not its minimum, maximum or format. Check those with if and throw InvalidArgumentException.

Best practices

Best practices

  • Start every new file with declare(strict_types=1); right after <?php, and add it to old files one at a time, with tests.
  • Convert and validate at the boundary where user input enters, so inner code works with cleanly typed values.
  • Do not use TypeError as a normal production flow; it signals a programmer mistake. Show users errors through validation instead.
  • Pick the most precise type available (?int, int|float, a class name) and keep mixed as a last resort.

Mini challenge

Mini challenge: a discount check in a strict file

Write a discount function in a strict file. Convert form text to an int at the boundary, and catch TypeErrors from badly typed calls so they display a clean message.

  • Make declare(strict_types=1) the first statement of the file
  • discountedPrice(float $price, int $percent): float applies the discount and rounds to 2 decimals
  • toInt(string $raw): ?int uses filter_var() with FILTER_VALIDATE_INT and returns null when invalid
  • tryDiscount(mixed $price, mixed $percent): string catches TypeError and shows the text before ", called in" as rejected (...)
discount.php
<?php
// TODO: strict mode declaration goes here

function discountedPrice(/* TODO: float price, int percent */): float
{
    // TODO: price * (100 - percent) / 100, rounded to 2 decimals
}

function toInt(string $raw): ?int
{
    // TODO: trim, validate with filter_var, return null on failure
}

function tryDiscount(mixed $price, mixed $percent): string
{
    // TODO: call discountedPrice inside try; format with number_format
    // TODO: on TypeError, return the message cut before ", called in"
}

// TODO: a valid call, a string price, a string percent
// TODO: toInt(" 25 ") feeding a discount, and toInt("12abc") rejected

Expected: Expected output: 170.00 rejected (discountedPrice(): Argument #1 ($price) must be of type float, string given) rejected (discountedPrice(): Argument #2 ($percent) must be of type int, string given) 60.00 invalid percent

Show hint

tryDiscount declares its parameters as mixed, so no check happens there; the strict check happens when discountedPrice is called. strstr($message, ", called in", true) removes the file path. filter_var() returns false on failure, so turn false into null to match the ?int return type.

Show solution
discount.php
<?php
declare(strict_types=1);

function discountedPrice(float $price, int $percent): float
{
    return round($price * (100 - $percent) / 100, 2);
}

function toInt(string $raw): ?int
{
    $value = filter_var(trim($raw), FILTER_VALIDATE_INT);
    return $value === false ? null : $value;
}

function tryDiscount(mixed $price, mixed $percent): string
{
    try {
        return number_format(discountedPrice($price, $percent), 2);
    } catch (TypeError $e) {
        return "rejected (" . strstr($e->getMessage(), ", called in", true) . ")";
    }
}

echo tryDiscount(200, 15), "\n";
echo tryDiscount("200", 15), "\n";
echo tryDiscount(200.0, "15"), "\n";
$percent = toInt(" 25 ");
echo $percent === null ? "invalid percent" : tryDiscount(80.0, $percent), "\n";
echo toInt("12abc") === null ? "invalid percent" : "ok", "\n";

Quick quiz 1 / 3

In a strict file, with function half(float $n): float { return $n / 2; }, what does echo half(5); do?

Quick quiz 2 / 3

lib.php has declare(strict_types=1) and defines function twice(int $n): int. main.php has no declare and calls twice("21"). What happens?

Quick quiz 3 / 3

Where must declare(strict_types=1); be placed?

What to remember

  • The default (weak) mode converts compatible scalars such as "5", true, 5.0 and "1e2" to int, and throws a TypeError only for values like "abc" and null.
  • declare(strict_types=1) must be the first statement of a file and makes calls from that file accept exact scalar types only (int to float is the one exception).
  • Arguments are checked with the file that writes the call and returns with the file that declares the function; callbacks invoked by built-in functions stay weak.
  • Strict types are not validation: convert form strings at the boundary with filter_var() and check value ranges yourself.

PHP Type Declarations — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.