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

คำสั่ง declare ใน PHP

บทนำ

Syntax ของ declare Statement ใน PHP คล้าย Flow Control Structures (while, for, foreach) ใช้กำหนด Directives สำหรับ Block ของโค้ด

Syntax

declare (directive) {
    statement1;
    statement2;
    ...
}

มี 3 Directives: ticks, encoding, strict_types

1. Ticks Directive

Tick = Event ที่เกิดทุก N Statements ใช้ register_tick_function() ลงทะเบียน Function ที่จะรันทุก Tick:

<?php
function myfunction() {
    echo "Hello World\n";
}
register_tick_function("myfunction");

declare (ticks=5) {
    for ($i = 1; $i <= 10; $i++) {
        echo $i . "\n";
    }
}
?>

ผลลัพธ์ (CLI)

1
2
3
4
5
Hello World
6
7
8
9
10
Hello World

มี unregister_tick_function() สำหรับยกเลิกการ Register

2. strict_types Directive

PHP เป็น Weakly Typed พยายาม Coerce Types อัตโนมัติ (เช่น Float → Int) ใช้ declare(strict_types=1) เพื่อป้องกัน Coercion (ต่อ File Basis):

<?php
// strict_types = 0 (default)
function myfunction(int $x, int $y) {
    return $x + $y;
}
echo "total=" . myfunction(1.99, 2.99);  // Coerce เป็น 1+2=3
?>

ผลลัพธ์

total=3

เปิด strict_types:

<?php
declare (strict_types=1);

function myfunction(int $x, int $y) {
    return $x + $y;
}
echo "total=" . myfunction(1.99, 2.99);
?>

ผลลัพธ์ (Error)

Fatal error: Uncaught TypeError: Argument 1 passed to myfunction() must be of the type integer, float given

3. Encoding Directive

ระบุ Encoding Scheme ของ Script:

<?php
declare(encoding='ISO-8859-1');
echo "This Script uses ISO-8859-1 encoding scheme";
?>

ข้อสังเกตสำคัญ

  • strict_types แทรกได้เฉพาะบนสุดไฟล์ (ก่อน Namespace) - File-scoped
  • ticks ใช้ได้ใน Block Scope
  • encoding ต้องอยู่บนสุด และ Script ต้องไม่มี BOM
  • Declare Block สามารถ Nest ได้ (Inner Override Outer)
  • strict_types=1 ส่งผลต่อ Function Calls ในไฟล์นั้นเท่านั้น (ไม่รวม Included Files)

Best Practice

  • ใช้ declare(strict_types=1); บนสุดทุกไฟล์ PHP ในโปรเจกต์ใหม่
  • ช่วยจับ Bug Type-related ได้เร็วขึ้น
  • Ticks ใช้น้อยมักใช้สำหรับ Profiling/Debugging