Categories
PHP

Strict Typing Mode

In PHP the declare(strict_types = 1); directive enables strict mode. In strict mode, only a variable of the exact type of the “type declaration” will be accepted, or a TypeError will be thrown.

The default behavior in PHP is to attempt to convert scalar values of incorrect type into the expected type. For example, a function expecting a string can still be called with an integer argument, because an integer can be converted into a string as shown in the following example:

<?php

function getString(string $str) {
 var_dump($str);
}

$int = 12;
getString($int);
//string(2) "12"

Without strict typing, PHP will change the integer 12 to string "12". In strict mode, only a variable of the exact type of the type declaration will be accepted, or a TypeError will be thrown:

<?php

declare(strict_types = 1);

function getString(string $str) {
 var_dump($str);
}

$int = 12;
getString($int);

//Fatal error: Uncaught TypeError: Argument 1 passed to getString() must be of the type string, integer given...

The only exception to this rule is that an integer may be given to a function expecting a float. Function calls from within internal functions will not be affected by the strict_types declaration:

<?php
declare(strict_types = 1);

function getFloat(float $f) {
 var_dump ($f);
}

$int = 100;
var_dump($int);
//int(100)

getFloat($int);
//float(100)

declare(strict_types=1); affects both parameters and return type declarations of scalar type, which must then be of the exact type declared in the function:

<?php
declare(strict_types = 1);

function getFloat(float $f) : int 
{
 return (int) $f;
}

$int = getFloat(100);

Note: You must configure the declare(strict_types = 1); statement in the first line of your code, or else it will generate a compile error. Also, it does not affect the included files, you need to declare the declare(strict_types = 1); statement on the top of each file.


Data types in PHP:

  1. Data Types
  2. Determine Variable Data Type
  3. Type Conversion: Convert variable data type
  4. Type Declaration
  5. Strict Typing Mode
  6. Testing, setting, and unsetting variables