Scalar Types in PHP

Scalar types in PHP is a new feature to PHP 7. Whilst on the surface its very easy to implement and uses very little code its actually an extremely powerful tool.

Scalar types in PHP is a very simple concept, you declare what type a¬†parameter should be and if it doesn’t match it will trigger a fatal¬†error. Lets consider the following code:

function addNumbers(int $num_1, int $num_2)
{
    return $num_1 + $num_2;
}

A very simple function to add two numbers, but notice in the function parameters we pre-pend each parameter with the word int. This tells PHP that we are expecting an integer and if its not an integer then trigger an error.

addNumbers(4, 5)

The above code will work fine where as the following code will trigger an error.

addNumbers(4, 'some string')

A word of warning, by default PHP will not use strict mode so it will try and convert types if it can, so the below code will actually work and not trigger an error.

addNumbers('4', 5)

PHP will convert the string of 4 into an integer and continue executing without error. This isn’t always helpful but we can change this behaviour by declaring strict_types at the top of our script, this only works on the current file where you declare it.

declare(strict_types=1);

function addNumbers(int $num_1, int $num_2)
{
    return $num_1 + $num_2;
}

So now if we try and pass a string it will trigger an error:

addNumbers('4', 5)

This is a brilliant addition to PHP and can really help to keep consistency across large applications. The available types at current are:

  1. bool
  2. float
  3. int
  4. string

Leave a Reply

Your email address will not be published. Required fields are marked *