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

Câu lệnh include trong PHP

Giới thiệu

Code PHP trong một file có thể dùng trong script khác nhờ câu lệnh include. Tính năng này cho phép phát triển modular bằng cách viết function/class một lần và gọi ở đâu cần thiết.

Câu lệnh include 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_WARNING và tiếp tục thực thi module gọi.

File được include có thể truy cập biến định nghĩa trong module gọi trước khi include. Những biến này có scope global.

Ví dụ

include thành công

<?php
echo "inside main script\n";
$var1 = 100;
echo "now calling test.php script\n";
include "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

Warning khi include thất bại

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

Kết quả

inside main script
now calling nosuchfile.php script
PHP Warning: include(nosuchfile.php): failed to open stream: No such file or directory in line 5
PHP Warning: include(): Failed opening 'nosuchfile.php' for inclusion (include_path='C:\xampp\php\PEAR') in line 5
returns from nosuchfile.php

include từ bên trong function

Nếu include file bên trong function, code trong file include được coi như phần của function. Do đó biến trong file include không truy cập được bên ngoài function.

// main script
<?php
function myfunction() {
    $var1 = 100;
    include "test.php";
    echo $var1 + $var2 . "\n";
}
myfunction();
echo "variable from included file outside function: $var2";
?>

// test.php included
<?php
echo "test.php called from inside function\n";
$var2 = 200;
return;
?>

Kết quả

test.php called from inside function
300
PHP Notice: Undefined variable: var2 in ... on line 9
variable from included file outside function

return từ include file

include trả về TRUE nếu thành công, FALSE nếu thất bại. Nếu file include explicit return expression, module gọi dùng được giá trị đó.

// main script
<?php
$result = include "test.php";   // có return expression
echo "return value: $result\n";
$y = include "test1.php";       // chỉ có return
echo "return value: $y\n";
$x = include "test2.php";       // không có return
echo "return value: $x\n";
?>

// test.php
<?php $var = 100; return $var; ?>
// test1.php
<?php $var = 100; return; ?>
// test2.php
<?php $var = 100; ?>

Kết quả

return value: 100
return value: 
return value: 1