Few years back, I have written article on Type Hinting with PHP. In that, I have clearly mentioned that type hinting is not possible with scalar data types like integer, string, float and booleans.
But with PHP 7, it is not possible to set type hinting for Scalar Data Types. This is introduced at two levels, which are scalar type hinting for function/method arguments and scalar type hinting for function/method return type.
Same as earlier we can define type hinting for scalar data types as well, let’s see that in code block below:
In the above code you can see that we have type hinting is defined as an integer but an argument is passed as string (Note the quotes). It’s because type hinting in PHP 7 is non-restrictive, which means PHP will correct parameter on its own. That is the reason it is not generating any kind of error and/or warnings.
We can enable this strictness by declaring declare directive like below:
With PHP7, same as above section we can define type hinting for function return type as well. Type hinting for function return type is a new introduction for PHP world.
Same as argument type hinting, this type hinting is also non-restrictive and we can enable the strictness as mentioned in the above section. Let’s look into some code now:
The above code will not generate any error/warning and continue execution by converting the return value to the defined return type. For the script mode same code can be written as below:
Hope you find this piece of PHP 7 interesting and useful but for now let’s wait and watch for PHP 7 stuff.
Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.
View all posts by: Avinash