บทนำ
คำสั่ง require_once ใน PHP ทำงานคล้ายกับคำสั่ง require ความแตกต่างคือ หากไฟล์ถูก include ไปแล้วสำหรับการประมวลผล จะไม่ถูก include อีกครั้ง โปรดทราบว่า ไฟล์ที่ include ด้วย include หรือ require statement ก็จะไม่ถูก include อีกครั้งแม้จะใช้ require_once statement
พฤติกรรมอื่นๆ ของ require_once คล้ายกับ require statement
ตัวอย่าง require_once
ในตัวอย่างต่อไปนี้ main php script include test.php:
ตัวอย่าง
<?php echo "inside main script\n"; echo "now including with require_once test.php script\n"; require_once "test.php"; echo "try to include it again"; require_once "test.php"; ?> //test.php <?php echo "File included\n"; ?>
ผลลัพธ์
inside main script now including with require_once test.php script File included try to include it again
ข้อผิดพลาดเมื่อ require_once ล้มเหลว
require_once statement ก็ทำให้เกิด fatal error เมื่อพยายาม include ไฟล์ที่ไม่มีอยู่:
ตัวอย่าง
<?php echo "inside main script\n"; echo "now including with require_once notest.php script\n"; require_once "notest.php"; ?>
ผลลัพธ์
inside main script now including with require_once notest.php script PHP Fatal error: require_once(): Failed opening required 'notest.php' (include_path='C:\xampp\php\PEAR') in line 4 Fatal error: require_once(): Failed opening required 'notest.php' (include_path='C:\xampp\php\PEAR') in line 4