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

PHP require_once Statement


แนะนำตัว

require_once คำสั่งใน PHP นั้นคล้ายกับคำสั่งที่ต้องใช้ ข้อแตกต่างเพียงอย่างเดียวคือ หากไฟล์ถูกรวมไว้สำหรับการประมวลผลแล้ว ไฟล์นั้นจะไม่ถูกรวมเข้าไปอีก โปรดทราบว่าไฟล์ที่รวมอยู่ในคำสั่ง include หรือ require จะไม่ถูกรวมอีกแม้ว่าจะใช้คำสั่ง require_once ก็ตาม

ลักษณะการทำงานอื่น ๆ ของคำสั่ง require_once คล้ายกับคำสั่ง require .

require_once ตัวอย่าง

ในตัวอย่างต่อไปนี้ สคริปต์ php หลักประกอบด้วย 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 ทำให้เกิดข้อผิดพลาดร้ายแรงเมื่อพยายามเพิ่มไฟล์ที่ไม่มีอยู่

ตัวอย่าง

<?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