Frank Perez

Frank Perez

Keep in touch

An experienced Web Developer with years of experience in design, programming and server administration.

Blog

Overview

© 2018 by Frank Perez.

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.

<?php

class Calculator
{
    public function sum(float ...$numbers)
    {
        return array_sum($numbers);
    }
}

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

<?php

$calculator = new Calculator();

try {
    echo $calculator->sum(5, 10.2);
} catch (TypeError $e) {
    echo $e->getMessage();
}

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.

<?php

$calculator = new Calculator();

try {
    echo $calculator->sum(5, 10.2, 7, 9, 8);
} catch (TypeError $e) {
    echo $e->getMessage();
}

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.

<?php

$calculator = new Calculator();

try {
    echo $calculator->sum(5, 10.2, 'test');
} catch (TypeError $e) {
    echo $e->getMessage();
}

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%