PHP include and require

PHP include and require 使用

include/require 是用來將其他 PHP file 引入其他的 PHP file中,假設你有一段相同的code要使用在許多 PHP file中,就會需要用到 include/require。

include / require

include 和 require 使用上的差異:
include: 檔案不存在時只會警告,繼續往下執行程式,常用於流程控制中。
require: 檔案不存在時會產生錯誤,程式會停止執行,常放於常放於文件的開頭,引入一些必要的靜態檔案。

Syntax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
include 'filename';
or
require 'filename';
//假設我們有一個 footer.php,內容如下:
<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>
// 將 footer.php放入其他 php 檔案。
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body>
</html>
/*
輸出結果:
Welcome to my home page!
Some text.
Some more text.
Copyright © 1999-2017 W3Schools.com
*/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Example 2
// 假設我們有一個 menu.php如下:
<?php
echo '<a href="/default.asp">Home</a> -
<a href="/html/default.asp">HTML Tutorial</a> -
<a href="/css/default.asp">CSS Tutorial</a> -
<a href="/js/default.asp">JavaScript Tutorial</a> -
<a href="default.asp">PHP Tutorial</a>';
?>
// 放入下方的php檔案中的 div tag 中
<html>
<body>
<div class="menu">
<?php include 'menu.php';?>
</div>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
</body>
</html>
/* 輸出結果:
Home - HTML Tutorial - CSS Tutorial - JavaScript Tutorial - PHP Tutorial
Welcome to my home page!
Some text.
Some more text.
*/

include_once / require_once

跟 include / require 的差異在於,會判斷檔案是否被載入過,如果尚未被載入才會載入此檔案。

Syntax

1
2
3
include_once 'filename';
or
require_once 'filename';