DEV Community

Cover image for Scalar Type Declaration
Ashish Ranade
Ashish Ranade

Posted on

Scalar Type Declaration

Today, I like to share some of the key features provided in PHP. The PHP community has introduced some good features like Scalar type declaration, Return type declarations, etc.., which add some extra features to the PHP development, and provides flexibility in the development lifecycle. In this blog, I would like to explain the Scalar type declaration feature, I hope this will help you to improve your knowledge and help you somehow in the future.

Scalar Type Declaration

Type declaration is also known as Type Hinting, allows a function to accept a parameter of a certain type if the given value is not of the correct type (Integer, Float, Boolean, string) PHP will return a fatal error. The older version of PHP (PHP 5) gives a recoverable error while the new release (PHP 7) returns a throwable error.

PHP 7 has introduced the following Scalar type declarations.

1.Boolean
2.String
3.Float
4.Integer
5.Iterable
Scalar Type Declaration comes in two types Coercive(i.e. default), and another one is Strict, if we want to enforce PHP to use a strict type declaration then, we should set the strict value to 1 using a declare directive, please check the example below.

declare(strict_types=1);
Please check the example below for Coercive and Strict type declarations.

Coercive Scalar Type Declaration

try{
     function sum(int …$ints) 
     {
         return array_sum($ints);
     }
}catch(Exception $ex)
{
   echo $ex->getMessage();
}
print(sum(2, ‘3’, 4.1));

In the above example just want to highlight one thing i.e. we are not using a strict value for parameter type like 2 of Integer type, 3 of String type 4.1 of Float type. The above code will output the value int(9).

Strict Scalar Type Declaration

declare(strict_types=1);
try {
      function sum(int …$ints) 
      {
         return array_sum($ints);
      }
} catch (Exception $ex) 
{   
   echo $ex->gt;
   getMessage();
}
print(sum(2, ‘3’, 4.1));

Note that, if we declare the strict_type value to 1, the above code will output “Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string is given”.

The above code will help us to enforce the other developer to use a variable of strict type i.e. Integer, Float, etc.

Use of Scalar Type Declaration

The scalar type declaration can be used in different areas of development, like, defining strict values in an interface, so that, the child class which is overriding the interface must follow the strict type.

I hope that will help you somehow. Feel free to leave a comment below. Let me know what you think about this

Oldest comments (0)