PHP 7 Scalar Type Declaration

PHP Scalar Type Declaration is a new feature added in PHP 7. As we know, PHP is a loosely-typed language. There is no need to define a datatype of a variable before assigning them to a value. But, PHP7 has added the type declaration, which is called scalar type declaration. It is applicable to scalar types: strings, integer, float, boolean.

Simply type declaration means to specify the type of the variable instead of PHP setting it automatically. Previously, we can pass a string in an integer data type and PHP did not give any error. That considered PHP a very weak-typed language. So scalar type declaration makes us to receive expected results.

Types of Scalar type declarations

There are two types of scalar type declarations-

  • Coercive (default)
  • Strict




Coercive type declaration

The coercive type is a non-strict type declaration. If we provide the value of different data types from the specified data type, then PHP casts them to match the types specified in the function.

Example

function getAddition(float $i, float $j)
{
	return $i + $j;
}
getAddition(10, "1 month")
// In Coercive : 10 changed to 10.0 and "1 month" changes to 1.0, 
// and it returns NOTICE with return value. 
Notice: A non well formed numeric value encountered.
11

Strict type declaration

The strict type declaration is strict to the specified data type. It returns a fatal error if we provide the values of different data types from the specified data type.

To use the strict type declaration, we first make the strict mode ON in the desired file. This is done by adding the following code at the top of the file.

declare(strict_types=1);

Example

function getAddition(int $i, int $j)
{
	return $i + $j;
}
getAddition(10, "1 month")
// In strict mode, it returns fatal error. 
Fatal error: Uncaught TypeError: Argument 2 passed to getAddition() must be of the type int, string given

Strict return type declaration.

PHP 7 also provides us with the opportunity to specify the data type of value that a function should return.

Example

function getAddition(int $i, int $j): int
{
	return $i + $j;
}

If the strict mode is not ON and the return value type is different than the specified type. PHP casts the return value to match the specified type.

function getAddition(int $i): int
{
	return $i + 11.2;
}
getAddition(10);
// Output : 21, php casts (11.2) to 11

If the strict mode is ON and the return value type is different than the specified type. PHP returns FATAL error.

function getAddition(int $i): int
{
	return $i + 11.2;
}
getAddition(10);
// Fatal error: Uncaught TypeError: Return value of getAddition() must be of the type integer, float returned






Read more articles


General Knowledge



Learn Popular Language