Skip to content

PHP Tutorial Data Types

Strict Typing

Lesson 46 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

By default, PHP is forgiving with function arguments. If a function asks for an int and you pass the string "5", PHP converts it for you.

index.php
PHP
<?php
function double(int $n): int
{
    return $n * 2;
}

echo double("5");
Output
OUTPUT
10

That works, but it can hide mistakes. With strict typing turned on, PHP refuses to convert.

Turn on strict types

Put this line at the very top of the file, right after <?php:

index.php
PHP
<?php
declare(strict_types=1);

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

try {
    echo double("5");
} catch (TypeError $e) {
    echo "Error: " . $e->getMessage();
}
Output
OUTPUT
Error: double(): Argument #1 ($n) must be of type int, string given, called in /path/to/index.php on line 10

Now a string cannot sneak in as an int. You get a clear TypeError right where the bad value entered.

What strict types changes

  • Calls to your functions are checked exactly.
  • Calls to built-in functions from this file are checked exactly too.
  • Return values are checked exactly.

One small exception: an int is still allowed where a float is expected, because it loses no information.

What strict types does not change

  • It does not change +, == or other operators. "5" + 5 still works.
  • It applies per file. A file without the line stays in the forgiving mode, even if it calls code from a strict file.

Why use it

Mistakes appear when you write them instead of three pages later. Most modern PHP projects and frameworks start every file with this line.

index.php
PHP
<?php

declare(strict_types=1);

namespace App;
dangerous
It must be the first statement
declare(strict_types=1); has to come before any other code in the file. If there is output or other code before it, PHP throws a fatal error.

Exercise: spot the error

With strict types on, which of these calls would throw a TypeError for function show(string $text): show("hi"), show(5), show("5")?

Show the answer

Only show(5) throws, because 5 is an integer and the function wants a string. "hi" and "5" are both strings.