Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Câu lệnh include_once trong PHP

Giới thiệu

Giống như include, include_once cũng chuyển giao và đánh giá script từ file này sang file khác. Khác biệt: include_once ngăn file tải lại nếu đã include rồi. Như tên gọi, file chỉ được include một lần ngay cả khi gọi include nhiều lần.

include_once thường dùng để thiết lập biến global, nạp thư viện, hoặc hoạt động kỳ vọng chạy một lần ở đầu ứng dụng.

Ngoài ra, hành vi include_once giống include.

Ví dụ

include_once cơ bản

<?php
echo "calling include_once statement\n";
$result = include_once "test.php";
?>

// test.php
<?php
echo "This file is included once\n";
?>

Kết quả

calling include_once statement
This file is included once

Warning khi include_once thất bại

Parser phát warning nếu file argument không tìm thấy:

<?php
echo "inside main script\n";
$var1 = 100;
echo "now calling nosuchfile.php script";
include_once "nosuchfile.php";
echo "returns from nosuchfile.php";
?>

Kết quả

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

Gọi include_once lần 2

File không bị include lại:

// main script
<?php
echo "inside main script\n";
echo "now including test.php script\n";
include_once "test.php";
echo "now including again test.php script\n";
?>

// test.php included
<?php
echo "This file is included once";
?>

Kết quả

inside main script
now including test.php script
This file is included once
now including again test.php script