Tìm hiểu Include và Required trong PHP
5:00 read
PHP Include và Require (PHP Include and Require)
Trong PHP, include
và require
là hai hàm quan trọng được sử dụng để chèn nội dung của một tệp PHP vào một tệp PHP khác. Điều này giúp tái sử dụng mã và tổ chức mã nguồn một cách hiệu quả hơn.
Sự khác biệt giữa Include và Require
include
Hàm include
được sử dụng để chèn nội dung của một tệp vào tệp hiện tại. Nếu tệp không tồn tại, PHP sẽ tạo ra một cảnh báo (warning) nhưng vẫn tiếp tục thực thi mã.
Cú pháp
include 'filename.php';
require
Hàm require
cũng được sử dụng để chèn nội dung của một tệp vào tệp hiện tại. Tuy nhiên, nếu tệp không tồn tại, PHP sẽ tạo ra một lỗi nghiêm trọng (fatal error) và dừng thực thi mã.
Cú pháp
require 'filename.php';
Sự khác biệt chính
include
: Tạo ra cảnh báo nếu tệp không tồn tại và tiếp tục thực thi mã.require
: Tạo ra lỗi nghiêm trọng nếu tệp không tồn tại và dừng thực thi mã.
Ví dụ sử dụng Include và Require
Sử dụng include
// filepath: header.php
<!DOCTYPE html>
<html>
<head>
<title>My Website</title>
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
</header>
// filepath: footer.php
<footer>
<p>© 2023 My Website</p>
</footer>
</body>
</html>
// filepath: index.php
<?php
include 'header.php';
?>
<main>
<p>This is the main content of the page.</p>
</main>
<?php
include 'footer.php';
?>
Sử dụng require
// filepath: config.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
?>
// filepath: db_connect.php
<?php
require 'config.php';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Yêu cầu đăng nhập
Vui lòng đăng nhập để truy cập nội dung này
Additional Resources
Course Guide
Comprehensive PDF guide with examples
GitHub Repository
Example code for all lessons
Discussion
Have a question about this lesson? Post it here and get answers from instructors and peers.