In PHP, the scalar type casting can be used to convert a value to a specific type by placing the desired type in parentheses before the value. PHP has long supported multiple casting syntaxes. For example, we can cast a variable to an integer using either (int) or (integer). PHP scalar types have the following alternate forms:
| No. | Canonical cast | Alternative form |
|---|---|---|
| 1. | (int) | (integer) |
| 2. | (float) | (double) |
| 3. | (bool) | (boolean) |
| 4. | (binary) | (string) |
Since PHP 8.5, non-canonical scalar type casts are deprecated. This means the following code will trigger deprecation warnings:
<?php
$val = '1';
$val2 = 1;
$int = (integer) $val;
$float = (double) $val;
$bool = (boolean) $val;
$string = (binary) $val2;
Example will output:
Deprecated: Non-canonical cast (integer) is deprecated, use the (int) cast instead ...
Deprecated: Non-canonical cast (double) is deprecated, use the (float) cast instead ...
Deprecated: Non-canonical cast (boolean) is deprecated, use the (bool) cast instead ...
Deprecated: Non-canonical cast (binary) is deprecated, use the (string) cast instead ...
In the previous example, a deprecation warnings can be fixed using canonical casts:
<?php
$val = '1';
$val2 = 1;
$int = (int) $val;
$float = (float) $val;
$bool = (bool) $val;
$string = (string) $val2;
Leave a Comment
Cancel reply