Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

Type Hinting ใน PHP 7

PHP 7 ใช้ type hinting สองประเภทในการประกาศ scalar type และ return type declaration -

  • Weak type hinting
  • Strict type hinting

Weak type hinting

โดยค่าเริ่มต้น PHP 7 ทำงานในโหมด weak type checking Weak type checking จะไม่ให้ข้อผิดพลาดหรือ fatal error เมื่อเกิด type declaration mismatch จะ execute โค้ดต่อไปโดยไม่โยนข้อผิดพลาด

ด้วยการใช้ declare(strict_types()) เราสามารถควบคุม weak type checking ได้

declare(strict_types=0); // weak type-checking; ตั้งค่า strict = 0

ตัวอย่าง Weak type hinting ที่ 1

<?php 
    $x=10; // integer variable x = 10 value 
    $y=20.20; // ใช้ floating point number y = 20.20 value 
    function add(int $x, int $y){ 
        return $x + $y; 
    } 
    echo add($x, $y); 
?>

ผลลัพธ์

โค้ดจะผลิตเอาต์พุตดังนี้ -

30

คำอธิบาย

ในตัวอย่างด้านบน เราไม่ได้ใช้ strict value สำหรับพารามิเตอร์ เราใช้ตัวแปร integer สองตัว x และ y สำหรับ x=10 และ y ใช้ floating number 20.20 แต่ y จะไม่ผลิตข้อผิดพลาด จะเพียงให้ค่าเอาต์พุต integer 30

ตัวอย่างที่ 2

<?php 
    function returnadd(int ...$integers){ 
        return array_sum($integers); 
    } 
    var_dump(returnadd(2, '3', 4.1)); 
?>

ผลลัพธ์

ผลลัพธ์สำหรับโปรแกรมด้านบนจะเป็น -

int(9)

Strict type hinting

Strict type hinting จะให้ Fatal Error เมื่อเกิด type declaration mismatch เราสามารถพูดได้ว่า strict type hinting ยอมรับตัวแปรของประเภทที่ตรงกับ type declaration เท่านั้น มิฉะนั้นจะโยน TypeError mismatch

ใน strict type hinting คำสั่งแรกในไฟล์ต้องประกาศ (strict_types=1) มิฉะนั้นจะเกิด compiler error มันไม่ส่งผลต่อไฟล์ included อื่นๆ ที่ไม่ได้ระบุในไฟล์ หมายความว่ามันส่งผลต่อไฟล์เฉพาะที่ใช้งาน

Strict type hinting directive เป็น compile-time ทั้งหมด และไม่สามารถควบคุมได้ใน runtime

ตัวอย่าง 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 
?>

ผลลัพธ์

โปรแกรม strict type hinting ด้านบนจะเป็น -

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

ตัวอย่าง Strict type hinting ที่ 2

<?php 
    declare(strict_types=1); // strict mode checking 
    $x='1'; // string 
    $y=20; // integer number 
    function add(int $x, int $y){ 
        return $x + $y; 
    } 
    var_dump(add($x, $y)); 
?>

จะผลิตเอาต์พุต "fatal error"

ในตัวอย่าง strict type declaration ด้านบน หากเราประกาศ strict_type value เป็น 1 โค้ดจะให้เอาต์พุต "Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type int, a string is given"