Strict typing
suggest changeSince PHP 7.0, some of the harmful effects of type juggling can be mitigated with strict typing. By including this declare statement as the first statement in the file, PHP enforces parameter and return type declarations. A mismatch throws a TypeError, which extends Error, not Exception.
declare(strict_types=1);
For example, this code, using parameter type declarations, throws a TypeError when run:
<?php
declare(strict_types=1);
function sum(int $a, int $b) {
return $a + $b;
}
echo sum("1", 2);
A return type is checked too. This call throws a TypeError even without strict_types, because "this is a string" cannot be coerced to int. A numeric string such as "1" is coerced to 1 unless strict types are on:
<?php
declare(strict_types=1);
function returner($a): int {
return $a;
}
returner("this is a string");
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents