PHP

Strict typing mode

In PHP the declare(strict_types = 1); directive enables strict mode. In strict mode, only a variable of exact type of the “type declaration” will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float.

By default, PHP 7 works in weak mode, and will cast values of the other type into the expected scalar type if possible. 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 following example:

<?php

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

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

Without strict typing, php will change integer 12 to string "12".

In strict mode, only a variable of 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 parameter 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.

Advertisement:
Advertisement: