Scalar Type Hints in PHP

Starting with PHP 7.0, it’s now possible to declare scalar type hints for your method arguments. Previously, we we’re able to use array and callable, but now with PHP 7+, we have access to the following list.

  • bool
  • float
  • int
  • string

This allows you to build your class methods by explicitly defining the type of data that can be passed through. For instance, if you explicitly define that int’s should be passed within your method, you’d see a TypeError Exception thrown when a string was passed.

Example Usage

Let’s build a calculator capable of summing infinite numbers.

Now let’s try and use the above to see how it works.

The above will output 15.2 as the result. We can pass any number of arguments above.

Here’s another example with a few more arguments.

This example outputs 39.2 as expected.

Let’s try and break this code now. We’ll try by passing a string to see what happens.

If you run the above code you’ll see that it is caught by our catch block with the following message:

Argument 3 passed to Calculator::sum() must be of the type float, string given, called in CalculatorExample.php on line 17%