PHP will let you change a variable’s type at any moment, and there’s nothing you can do about it. While you can use data structures, argument type declaration, and return type declaration to save a lot of damage, you can still change types.
<?php
declare(strict_types=1);
function showTypes(int $number) {
echo gettype($number) . "\n"; //integer
$number = "string";
echo gettype($number) . "\n"; //string
}
showTypes(2);
In order to help this situation a little bit, I’m using the appropriate type comparison operators and functions:
<?php
$number = 1;
// OK
if ($number > 0) {}
// Not OK
if (!$number) {}
if ($number === '') {}
if (strlen($number) > 0) {}
$string = 'Lorem ipsum';
// OK
if ($string === '') {}
if (strlen($string) > 0) {}
// Not OK
if (!$string) {}
$list = [];
// OK
if (count($list) > 0) {}
// Not OK
if (!$list) {}
$bool = false;
// OK
if (true === $bool) {}
if (!$bool) {}
// Not OK
if ($bool == '') {}
$var = null; // if I know a var can be null
// OK
if (null === $var) {}
if (is_null($var)) {}
// Not OK
if (!$var) {}
As such, I’m being more specific about the type variables are holding. In clean code it’s faster to see what a variable holds, but in legacy systems you can see a variable hundreds of lines later after declaration, or you can get a value from a function with no return type or DocBlock.
Treat each variable as close as possible to its type.