PHP - Scalar Type Declarations
Scalar type declarations in PHP allow you to specify the type of a function's parameters and return values, ensuring type safety and consistency within your code. PHP supports two main types of scalar type declarations: coercive and strict.
Coercive Type Declarations
Coercive type declarations allow PHP to automatically convert the provided argument to the specified type if
possible. These declarations are indicated by specifying the type name (e.g., int
,
float
, string
, bool
) directly in the function definition.
Function with Coercive Type Declarations
php<?php
function addNumbers(int $a, float $b): float {
return $a + $b;
}
echo addNumbers(5, 3.5); // Outputs: 8.5
?>
In the example:
int $a
: Specifies that the parameter$a
must be an integer. PHP will attempt to convert the provided value to an integer if possible.float $b
: Specifies that the parameter$b
must be a floating-point number. Again, PHP will attempt conversion if necessary.
Strict Type Declarations
Strict type declarations enforce type checking strictly without automatic type conversion. This ensures that
the function parameters and return values are of the specified types, and PHP throws a
TypeError
if the provided types do not match.
To enable strict type declarations for a file, add the following declaration at the beginning of your PHP script:
php<?php
declare(strict_types=1);
Example Using Strict Type Declarations
php<?php
declare(strict_types=1);
function addNumbers(int $a, float $b): float {
return $a + $b;
}
echo addNumbers(5, 3.5); // Outputs: 8.5
echo addNumbers(5, "3.5"); // TypeError: Argument 2 passed to addNumbers() must be of the type float
?>
In the strict mode example:
- Passing
"3.5"
as the second argument causes aTypeError
because"3.5"
is a string, not a float.
Summary:
Scalar type declarations in PHP (int
, float
,
string
,
bool
) allow you to enforce type safety in function parameters and return values. Coercive type
declarations (default behavior) allow type conversion where possible, while strict type declarations enforce
strict type checking without conversion. Understanding and using these declarations appropriately can help
improve the reliability and maintainability of your PHP applications.