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

Câu lệnh require_once trong PHP

Giới thiệu

Câu lệnh require_once trong PHP hoạt động tương tự require. Chỉ khác ở chỗ: nếu file đã được include để xử lý, nó sẽ không được include lại. File đã include bằng include hoặc require cũng sẽ không bị include lại nếu dùng require_once.

Hành vi khác của require_once giống hệt require.

Ví dụ

require_once cơ bản

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

Kết quả

inside main script
now including with require_once test.php script
File included
try to include it again

Lỗi khi require_once thất bại

require_once cũng gây fatal error khi file không tồn tại:

<?php
echo "inside main script\n";
echo "now including with require_once notest.php script\n";
require_once "notest.php";
?>

Kết quả

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'...