Strict Types

Ma Mahalakshmi V Updated 14 Nov 2026
6 min read ·Lesson 180 of 256

What Is Strict Typing?

In simple terms: By default, PHP is forgiving: if a function expects an integer and you pass the string '5', PHP quietly converts it to 5. That is convenient, but it can also hide bugs. Strict typing tells PHP to stop converting: values must already have the declared type, or PHP throws a TypeError.

Technically: PHP has two modes for checking scalar type declarations (int, float, string, bool):

ModeBehaviorHow to Enable
Coercive (default)Compatible values are converted to the declared typeNothing to do
StrictValues must match the declared type exactly (one exception: int is accepted for float)declare(strict_types=1); as the first statement of a file

The mode affects function and method calls (arguments), return values, and typed property assignments. Class and interface types are always checked strictly in both modes.


Coercive Mode (Default)

<?php
function add(int $a, int $b): int
{
    return $a + $b;
}

var_dump(add('5', '10'));
var_dump(add(5.0, 2));

try {
    add('five', 1);
} catch (TypeError $e) {
    echo strstr($e->getMessage(), ', called', true) . "\n";
}

Output

int(15)
int(7)
add(): Argument #1 ($a) must be of type int, string given
  • The numeric strings '5' and '10' are converted to integers.
  • The float 5.0 has no fractional part, so it is converted to 5. (Passing a float with a fractional part, such as 5.5, to an int parameter is deprecated since PHP 8.1.)
  • Even in coercive mode, values that cannot be converted meaningfully — like 'five' — throw a TypeError.

(The strstr() call only removes the "called in ... on line ..." part of the message, which contains file paths.)


Strict Mode

<?php
declare(strict_types=1);

function add(int $a, int $b): int
{
    return $a + $b;
}

function half(float $value): float
{
    return $value / 2;
}

var_dump(add(5, 10));
var_dump(half(5));   // int → float is allowed

$calls = [
    fn() => add('5', '10'),
    fn() => add(5.0, 2),
    fn() => strlen(123),
];

foreach ($calls as $call) {
    try {
        $call();
    } catch (TypeError $e) {
        echo strstr($e->getMessage() . ', called', ', called', true) . "\n";
    }
}

Output

int(15)
float(2.5)
add(): Argument #1 ($a) must be of type int, string given
add(): Argument #1 ($a) must be of type int, float given
strlen(): Argument #1 ($string) must be of type string, int given

How It Works

  1. declare(strict_types=1); must be the very first statement in the file (only the opening <?php tag may come before it).
  2. Calls made from this file are checked strictly: '5' is a string, not an int, so add('5', '10') throws.
  3. 5.0 is a float and is rejected for an int parameter.
  4. Built-in functions are checked strictly too: strlen(123) throws instead of converting 123 to '123'.
  5. The only conversion still allowed is int to float (half(5)), because it never loses information.

Return Types and Properties

In a strict file, return values and property assignments are checked strictly as well:

<?php
declare(strict_types=1);

function price(): int
{
    return '20';
}

class Product
{
    public int $stock = 0;
}

try {
    price();
} catch (TypeError $e) {
    echo $e->getMessage() . "\n";
}

try {
    $product = new Product();
    $product->stock = '15';
} catch (TypeError $e) {
    echo $e->getMessage() . "\n";
}

Output

price(): Return value must be of type int, string returned
Cannot assign string to property Product::$stock of type int

In coercive mode, both operations would succeed by converting '20' and '15' to integers.


The Mode Belongs to the Calling File

The most important (and most surprising) rule: for arguments, strict typing depends on the file where the call is written, not the file where the function is defined.

<?php
// lib.php — no strict_types declaration
function double(int $n): int
{
    return $n * 2;
}
<?php
// app.php
declare(strict_types=1);

require __DIR__ . '/lib.php';

double('4');   // TypeError: the call is in a strict file
<?php
// legacy.php — no declaration
require __DIR__ . '/lib.php';

double('4');   // int(8): the call is in a coercive file
CheckMode Determined By
Arguments passed to a functionThe file containing the call
Return valuesThe file containing the function definition
Property assignmentsThe file containing the assignment

This design lets strict and non-strict code coexist: a library can be used from strict application code and from older code without changes. In practice, modern projects simply declare strict types in every file.


What Strict Types Do Not Change

strict_types affects only type declarations. Other operations still convert values:

<?php
declare(strict_types=1);

var_dump('5' + 10);          // arithmetic still converts numeric strings
var_dump('10' == 10);        // loose comparison still converts
var_dump((bool) 'false');    // casting rules are unchanged

if ('0') {
    echo "never printed\n";  // truthiness rules are unchanged
} else {
    echo "'0' is falsy\n";
}

Output

int(15)
bool(true)
bool(true)
'0' is falsy

Use strict comparisons (===), explicit casts, and validation in addition to strict types.


Why Use Strict Types?

BenefitExplanation
Bugs surface earlyA string ID passed where an int is expected fails immediately, at the call site
No silent data changes'12abc' or true are never quietly turned into numbers
Clear contractsFunction signatures mean exactly what they say
Better toolingStatic analysis tools (PHPStan, Psalm) and IDEs give more precise feedback

Working With External Data

Request data ($_GET, $_POST), database results, and CSV files usually arrive as strings. In strict mode, convert and validate them once, at the boundary of your application:

<?php
declare(strict_types=1);

function loadProduct(int $id): string
{
    return "Product #$id";
}

$input = ['id' => '42'];   // like $_GET

$id = filter_var($input['id'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);

if ($id === false) {
    exit("Invalid product ID\n");
}

echo loadProduct($id) . "\n";

Output

Product #42

After validation, $id is a real int, and the rest of the code works with correct types.


Common Mistakes

Placing declare After Other Code

Effect: Fatal error: "strict_types declaration must be the very first statement in the script".

Fix: Put declare(strict_types=1); directly after <?php.

Passing Raw Request Strings to Typed Functions

Effect: TypeError in strict mode.

Fix: Validate and convert input at the application boundary.

Assuming Strict Types Affect Comparisons and Arithmetic

Effect: Loose comparisons (==) still convert values.

Fix: Use === and explicit casts.

Expecting the Defining File's Mode to Apply

Effect: A library with strict_types still accepts coerced arguments from non-strict callers.

Fix: Remember that the calling file decides how arguments are checked.


Best Practices

  • Add declare(strict_types=1); to every PHP file in new projects.
  • Convert and validate external input once, at the edges of the application.
  • Declare parameter, return, and property types everywhere.
  • Combine strict types with strict comparisons and static analysis.
  • Introduce strict types to legacy code file by file, starting with well-tested parts.

Official reference: https://www.php.net/manual/en/language.types.declarations.php#language.types.declarations.strict

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Tutorial Index PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions Modify Strings Concatenate Strings Slicing Strings Escape Characters String Interpolation Heredoc and Nowdoc Search in Strings Multibyte Strings PHP Floats PHP Casting PHP Type Juggling PHP Math PHP Random Numbers PHP Constants PHP Magic Constants PHP Operators Arithmetic Operators Assignment Operators Comparison Operators Increment / Decrement Operators Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence PHP If...Else...Elseif PHP If PHP If Operators PHP If...Else PHP Shorthand if PHP Nested if PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement Continue Statement PHP Functions User-defined Functions Function Arguments Default Argument Values Pass by Reference Named Arguments Variadic Functions Return Values Type Declarations in Functions Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET $_FILES $_COOKIE $_SESSION \$\_ENV PHP RegEx RegEx Patterns RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail Form Input Sanitizing Escaping Output (htmlspecialchars) Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions Error Handling Custom Error Handler Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators PHP What is OOP PHP Classes/Objects The $this Keyword PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Destructor PHP Access Modifiers Readonly Properties PHP Inheritance Method Overriding The final Keyword PHP Class Constants PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning Comparing Objects Anonymous Classes PHP Enums PHP Namespaces Autoloading Classes PHP Iterables Iterators Object Serialization Strict Types Union Types Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention CSRF Protection Session Security Secure Cookies File Upload Security Filesystem Security Error Reporting in Production Hiding PHP Encryption with Sodium PHP Configuration (php.ini) PHP Command Line (CLI) Composer PSR-4 Autoloading Installing Extensions (PECL / PIE) Debugging PHP OPcache & Performance Garbage Collection PHP-FPM Migrating to PHP 8 Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Image Upload Gallery Project: Shopping Cart with Sessions Project: Simple Blog Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about Strict Types and get answers drawn from it.

Signed-in readers only.