This email is part of a series where I talk about the most interesting features of PHP 8.
Today we talk about an important change affecting type checking. So, be sure to keep reading to make sure your code is ready for PHP 8.
We already talked a few times about type checking in PHP. PHP is a weakly-typed language that provides automatic type conversion. However, in recent versions, PHP has been introducing type-oriented features and rules to help developers work with specific types.
For instance, you can define the exact type of function arguments and return values. This wasn't possible with older PHP versions. PHP 8 also introduced Union Types, a new feature that we already covered in this email series.
So, it isn't surprising that PHP 8 has stricter rules about type hinting compared to PHP 7.
Let's see what's different and how you can make your code PHP 8 ready.
Type hinting and TypeError exceptions.
In PHP version 7, you can use type hinting for user defined function arguments. If you do so, and if you call that function passing arguments with the wrong type, PHP throws a TypeError exception, stopping the script execution if the exception is not caught.
However, in PHP 7, if you call a native function passing wrong argument types, most of the time PHP just raises an E_WARNING, and lets the script execution continue.
In PHP 8, this mechanism has been made more coherent and stricter. Now, using wrong argument types always makes PHP throw a TypeError exception, even for native functions.
For example, the following code raises an
E_WARNING in PHP 7, but it throws a TypeError exception in PHP 8:
$array = [1, 2, 3]; $len = strlen($array);
This new behavior is actually the same of PHP 7 when strict_types is set to 1. Now, in PHP 8, this is the default.
To make sure your code is ready for PHP 8, you must pay attention to call PHP functions with the correct argument types. This means that you should know exactly which values your variables hold (which is also important for security, as I explain in the very first chapter of my PHP security course).
Some automatic type conversions are still accepted in PHP 8. For instance, implicit conversions from numbers to numeric strings are accepted (we talked about how numeric strings have changed in PHP 8 in the last email).
However, if you try using a non-numeric string as a number, PHP 8 will throw a TypeError exception. Like in this case:
If you are not sure about the type of the variables you are using, you must catch TypeError exceptions to prevent the script from being terminated. This is how you can do it:
PHP Security Mastery What if you could write code that is always secure from attacks? Just imagine how this would increase your reputation and your possibilities as a developer. That is exactly what you will get from this course. You will learn to use the defense techniques that really work, leaving nothing to chance (with real code examples).