Scalar type declarations is one of the top feature added to PHP 7. There has been a big debate regarding correct way to use type declarations.
What is scalar type declaration in PHP 7?
Scalar type declarations means a function will accept arguments (parameters) or return values only of the given scalar data types.
How to declare Scalar type ?
To declare a scalar type declaration, you have to put scalar data type before the parameter name.
function Sum(int $a, int$b)
{
return $a + $b;
}
In the above example, PHP 7 interpreter will check first if $a and $b variables are integers. If $a and $b are integers then function will be called otherwise PHP 7 interpreter will generate a special type of TypeError exception.
Scalar type declaration has two options –
- Coercive – By default coercive mode is enabled. So, need not to be specify.
- Strict – Strict mode throws type error when the type doesn’t match.
Example of Coercive Mode
<?php
// Coercive mode
function mySum(int ...$ints) {
return array_sum($ints);
}
print(mySum(1, '2', 3.2));
//Output: 6
Example of Strict Mode
<?php
//Strict mode
declare(strict_types=1);
function mySum(int ...$ints) {
return array_sum($ints);
}
print(sum(4, 5, '2', 2.1));
//Output: Fatal error: Uncaught Error: Call to undefined function sum()....