One of the new features that PHP 7 will be bringing to the table is a feature called “scalar type hints”. In simple terms: You will be able to force what type of parameters your PHP functions can take in. For example: If you build a PHP function that is supposed to receive integer values, then you will be able to force this by using a scalar type hint.
Before we start; allow me to point out that a scalar type is a variable that contains a single value and that there are four scalar types in PHP. These are int, string, boolean and float.
Let’s have a look at a simple example.
Let’s say that our application allows users to guess a number between 1 and 10. For this application, we create a basic PHP function that tells the user whether his / her guess was correct or not:
<?php function guess($number){ $ourNumber = mt_rand(1, 10); if($number === $ourNumber){ return true; } return false; }
The function above receives the user’s guess as a parameter before returning a TRUE or FALSE boolean value. It basically generates a random number between 1 and 10 before comparing the result against the user’s input.
However, what if we want to make sure that the $number parameter is an integer value; and not a string, boolean or a float decimal value? Well, if you are using a PHP version that is lower than 7, then you would probably do one of the following:
- Parse the incoming variable as an integer.
- Check the type and throw an exception if the variable is not an integer.
However, if you are using PHP 7, then you will be able to make use of the new scalar type hints feature:
<?php function guess(int $number){ $ourNumber = mt_rand(1, 10); if($number === $ourNumber){ return true; } return false; }
If you look at the $number parameter, you will see that I have placed the word “int” in front of it. By doing this, I am telling my application that the $number parameter must be an integer value. If somebody uses the function incorrectly by passing in a string or a boolean value, that value will be automatically parsed as an integer.
If I want to be extra strict about how my function is used, then I can do the following:
<?php declare(strict_types=1); function guess(int $number){ $ourNumber = mt_rand(1, 10); if($number === $ourNumber){ return true; } return false; }
By declaring strict_types=1, I am telling my application that it should throw an error if the wrong variable type is passed as a parameter to my function.
Why would I do this? Well, maybe the function does something that is extremely important and I don’t want the developer to remain blissfully unaware about the fact that they are using it incorrectly. Maybe I want to prod the developer with a metaphorical stick and shout “Bold! That’s not how you use this function! Try again!”