บทนำ
เช่นเดียวกับคำสั่ง include include_once ก็โอนและประเมินสคริปต์ที่เขียนในไฟล์หนึ่งไปยังอีกไฟล์หนึ่ง ความแตกต่างของทั้งสองอยู่ที่ include_once ป้องกันไม่ให้ไฟล์เดียวกันถูกโหลดซ้ำหากทำไปแล้ว ตามที่ชื่อบ่งชี้ ไฟล์จะถูก include เพียงครั้งเดียว แม้จะพยายามสั่ง include อีกครั้ง
คำสั่ง include_once มักใช้เพื่อตั้งค่าตัวแปร global เปิดใช้งานไลบรารี หรือกิจกรรมที่คาดว่าจะทำในช่วงต้นของการดำเนินการแอปพลิเคชัน
นอกจากนี้ พฤติกรรมของ include_once statement คล้ายกับ include statement
ตัวอย่าง include_once
ในตัวอย่างต่อไปนี้ testscript.php อยู่ในโฟลเดอร์ document root ของ Apache server มัน insert test.php ด้วยคำสั่ง include_once:
ตัวอย่าง
<?php echo "calling include_once statement\n"; $result=include_once "test.php"; ?> //test.php <?php echo "This file is included once\n"; ?>
ผลลัพธ์
calling include_once statement
This file is included once
คำเตือนเมื่อ include ล้มเหลว
Parser แจ้งเตือน (warning) หากไฟล์อาร์กิวเมนต์ของ include_once statement ไม่พบ:
ตัวอย่าง
<?php echo "inside main script<br />"; $var1=100; echo "now calling nosuchfile.php script"; include_once "nosuchfile.php"; echo "returns from nosuchfile.php"; ?>
ผลลัพธ์
inside main script now calling nosuchfile.php script PHP Warning: include_once(nosuchfile.php): failed to open stream: No such file or directory in line 5 PHP Warning: include_once(): Failed opening 'nosuchfile.php' for inclusion (include_path='C:\xampp\php\PEAR') in line 5 returns from nosuchfile.php
การเรียก include_once อีกครั้ง
ตัวอย่างต่อไปนี้ include test.php ด้วยคำสั่ง include_once สังเกตว่าไฟล์เดียวกันไม่ถูก include อีกครั้ง:
ตัวอย่าง
//main script <?php echo "inside main script<br>"; echo "now including test.php script<br>"; include_once "test.php"; echo "now including again test.php script<br>"; ?> //test.php included <?php echo "This file is included once"; ?>
ผลลัพธ์
inside main script<br />now including test.php script<br />
This file is included once
now including again test.php script