PHP 7 dùng hai loại type hinting trong khai báo kiểu scalar và kiểu trả về:
- Weak type hinting (Kiểu yếu)
- Strict type hinting (Kiểu nghiêm ngặt)
Weak type hinting
Mặc định PHP 7 hoạt động ở chế độ weak type checking. Weak type checking không báo lỗi hay fatal error. Khi khai báo kiểu không khớp, chỉ thực thi code mà không ném lỗi.
Dùng declare(strict_types=0) để kiểm soát weak type checking.
declare(strict_types=0); // weak type-checking; set strict = 0
Ví dụ Weak type hinting 1
<?php
$x = 10; // biến nguyên x=10
$y = 20.20; // số thực y=20.20
function add(int $x, int $y) {
return $x + $y;
}
echo add($x, $y);
?>
Kết quả
30
Giải thích
Trong ví dụ trên, không dùng strict value cho tham số. Dùng hai biến nguyên x, y. Với x=10 và y là số thực 20.20, y không báo lỗi; chỉ cho ra giá trị nguyên 30.
Ví dụ 2
<?php
function returnadd(int ...$integers) {
return array_sum($integers);
}
var_dump(returnadd(2, '3', 4.1));
?>
Kết quả
int(9)
Strict type hinting
Strict type hinting báo Fatal Error khi khai báo kiểu không khớp. Có thể nói strict type hinting chỉ chấp nhận biến đúng kiểu khai báo, ngược lại ném TypeError mismatch.
Trong strict type hinting, câu lệnh đầu tiên trong file phải declare(strict_types=1), ngược lại báo lỗi compiler. Không ảnh hưởng file include khác không khai báo, nghĩa là chỉ ảnh hưởng file cụ thể dùng.
Chỉ thị strict type hinting hoàn toàn tại compile-time, không điều khiển tại runtime.
Ví dụ Strict type hinting 1
<?php
declare(strict_types=1);
function returnadd(float $x, float $y) {
return $x + $y;
}
var_dump(returnadd(3.1, 2.1)); // output float(5.2)
var_dump(returnadd(3, "2 days")); // fatal error
?>
Kết quả
float(5.2)
Fatal error: Uncaught TypeError: Argument 2 passed to returnadd() must be of the type float, string given, called in C:\xampp\htdocs\gud.php on line 7 and defined in C:\xampp\htdocs\gud.php:3 Stack trace: #0 C:\xampp\htdocs\gud.php(7): returnadd(3, '2 days') #1 {main} thrown in C:\xampp\htdocs\gud.php on line 3
Ví dụ Strict type hinting 2
<?php
declare(strict_types=1); // strict mode checking
$x = '1'; // chuỗi
$y = 20; // nguyên
function add(int $x, int $y) {
return $x + $y;
}
var_dump(add($x, $y));
?>
Sẽ cho ra output "fatal error"
Trong ví dụ strict type declaration trên, nếu khai báo strict_type=1, code cho output "Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type int, a string is given".