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

Câu lệnh require trong PHP

Giới thiệu

Hiệu ứng của require tương tự include. Tuy nhiên có một khác biệt chính: nếu parser không tìm thấy file, nó sinh ra fatal error khiến script hiện tại dừng hẳn. Câu lệnh include chỉ phát warning khi không tìm thấy file và tiếp tục thực thi.

PHP parser tìm file trong thư mục hiện tại mặc định, tiếp theo các thư mục trong include_path của php.ini. Nếu file không có ở cả hai nơi, PHP phát E_COMPILE_ERROR và dừng module gọi.

Ví dụ

require thành công

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

// test.php
<?php
$var2 = 200;
// truy cập $var1 từ main script
echo $var1 + $var2 . "\n";
?>

Kết quả

inside main script
now calling test.php script
300
returns from test.php

Lỗi khi require thất bại

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

Kết quả

inside main script
now calling nosuchfile.php script
PHP Fatal error: require(): Failed opening required 'nosuchfile.php' (include_path='C:\xampp\php\PEAR') in line 5
Fatal error: require(): Failed...