Devdit
 

PHP include กับ require แตกต่างกันยังไง ควรเลือกใช้แบบไหน

1.5K

คำสั่ง include และ require เป็นคำสั่งของภาษา PHP มีไว้สำหรับเรียกไฟล์อื่นเข้ามาทำงานในไฟล์ที่ต้องการ เช่น ไฟล์ index.php เรียกใช้ไฟล์ header.php, body.php หรือ footer.php เป็นต้น โดยทั้ง 2 คำสั่งมีความแตกต่างกันดังนี้

 

1. คำสั่ง include กรณีถ้าไม่พบไฟล์โปรแกรมจะขึ้น Warning ส่งผลทำให้โปรแกรมในบรรทัดต่อๆ ไปยังทำงานได้

2. คำสั่ง require กรณีถ้าไม่พบไฟล์โปรแกรมจะขึ้น Error ส่งผลทำให้โปรแกรมในบรรทัดต่อๆ ไปจะหยุดทำงาน

 

ตัวอย่าง include แบบไม่พบไฟล์แต่ยังพิมพ์ hello, world

include("headerx.php");
echo "hello, world";

ผลลัพธ์

Warning: include(headerx.php): Failed to open stream: No such file or directory in D:\xampp\htdocs\index.php on line 2
Warning: include(): Failed opening 'headerx.php' for inclusion (include_path='D:\xampp\php\PEAR') in D:\xampp\htdocs\index.php on line 2
hello, world

ตัวอย่าง require แบบไม่พบไฟล์ทำให้โปรแกรมหยุดทำงาน ไม่มีการพิมพ์ hello, world

require("headerx.php");
echo "hello, world";

ผลลัพธ์

Warning: require(headerx.php): Failed to open stream: No such file or directory in D:\xampp\htdocs\index.php on line 2
Fatal error: Uncaught Error: Failed opening required 'headerx.php' (include_path='D:\xampp\php\PEAR') in D:\xampp\htdocs\index.php:2 Stack trace: #0 {main} thrown in D:\xampp\htdocs\index.php on line 2
เขียน 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ