Table of Contents
include and require: " >include and require:
include and include_once:
Relative path: " >Relative path:
Absolute path: " >Absolute path:
" > Local absolute path:
" > Absolute network path:
" >No path:
当文件中有return:
Home Backend Development PHP Tutorial What are the ways to import files in PHP? Introduction to four methods of introducing files in PHP (code)

What are the ways to import files in PHP? Introduction to four methods of introducing files in PHP (code)

Jul 23, 2018 pm 05:09 PM

What are the ways to import files in PHP? The PHP import file has four statements: include, require, include_once, require_once. Let’s take a look at specific examples of PHP import files.

Basic syntax

require: require function is generally placed at the front of the PHP script and will be executed before PHP First read in the imported file specified by require, include and try to execute the imported script file. The way require works is to improve the execution efficiency of PHP. After it is interpreted once in the same web page, it will not be interpreted the second time. But similarly, because it will not repeatedly interpret the imported file, you need to use include when using loops or conditional statements to introduce files in PHP.

include: can be placed anywhere in the PHP script, usually in the processing part of the process control. When the PHP script is executed to the file specified by include, it will be included and attempted to execute. This method can simplify the process of program execution. When encountering the same file for the second time, PHP will still re-interpret it again. The execution efficiency of include is much lower than that of require. At the same time, when the user-defined function is included in the imported file, PHP will have the problem of repeated function definition during the interpretation process. .

require_once/include_once: The functions are the same as require/include respectively. The difference is that when they are executed, they will first check whether the target content has been imported before. If it has been imported, Then the same content will not be reintroduced again.

The difference between each other

include and require:

include has Return value, while require has no return value

When include fails to load a file, it will generate a warning (E_WARNING), and the script will continue to execute after the error occurs. So include is used when you want to continue execution and output results to the user.

//test1.php
<?php
include &#39;./tsest.php&#39;;
echo &#39;this is test1&#39;;
?>

//test2.php
<?php
echo &#39;this is test2\n&#39;;
function test() {
    echo &#39;this is test\n&#39;;
}
?>

//结果:
this is test1
Copy after login

require will generate a fatal error (E_COMPILE_ERROR) when loading fails, and the script will stop executing after the error occurs. Generally used when subsequent code depends on the loaded file.

//test1.php
<?php
require &#39;./tsest.php&#39;;
echo &#39;this is test1&#39;;
?>

//test2.php
<?php
echo &#39;this is test2\n&#39;;
function test() {
    echo &#39;this is test\n&#39;;
}
?>
Copy after login

Result:

What are the ways to import files in PHP? Introduction to four methods of introducing files in PHP (code)

include and include_once:

The files loaded by include will not be judged as duplicates , as long as there is an include statement, it will be loaded once (even if repeated loading may occur). When include_once loads a file, there will be an internal judgment mechanism to determine whether the previous code has been loaded. What needs to be noted here is that include_once is judged based on whether a file with the same path has been previously imported, rather than based on the content of the file (that is, the content of the two files to be imported is the same, and using include_once will still introduce two).

//test1.php
<?php
include &#39;./test2.php&#39;;
echo &#39;this is test1&#39;;
include &#39;./test2.php&#39;;
?>

//test2.php
<?php
echo &#39;this is test2&#39;;
?>

//结果:
this is test2this is test1this is test2


//test1.php
<?php
include &#39;./test2.php&#39;;
echo &#39;this is test1&#39;;
include_once &#39;./test2.php&#39;;
?>

//test2.php
<?php
echo &#39;this is test2&#39;;
?>

//结果:
this is test2this is test1


//test1.php
<?php
include_once &#39;./test2.php&#39;;
echo &#39;this is test1&#39;;
include &#39;./test2.php&#39;;
?>

//test2.php
<?php
echo &#39;this is test2&#39;;
?>

//结果:
this is test2this is test1this is test2


//test1.php
<?php
include_once &#39;./test2.php&#39;;
echo &#39;this is test1&#39;;
include_once &#39;./test2.php&#39;;
?>

//test2.php
<?php
echo &#39;this is test2&#39;;
?>

//结果:
this is test2this is test1
Copy after login

require and require_once: The same difference as include and include_once.

Execution process when loading

1. Exit php script mode from the include (require) statement (enter html code mode)

2. Load the code in the file set by the include statement and try to execute it

3. Exit the html mode, re-enter the php script mode, and continue the execution of the subsequent script program

//test1.php
<html>
<body>
主文件开始位置:
<?php
    echo "<br> 主文件中位置 A";
    include "./test2.php";    //要载入的文件
    echo "<br> 主文件中位置 B";
?>
<br> 主文件结束位置
</body>
</html>

//test2.php
<br> 被载入文件位置 1
<?php
echo "<br> 被载入文件位置 2";
?>
<br> 被载入文件位置 3
Copy after login

Result:What are the ways to import files in PHP? Introduction to four methods of introducing files in PHP (code)

Analysis:

What are the ways to import files in PHP? Introduction to four methods of introducing files in PHP (code)

##Path problem during loading

Relative path:

Locate the location of a loaded file relative to the location of the current web page file.

./  表示表示当前位置,即当前网页文件所在的目录
. . /  表示上一级位置,即当前网页文件所在目录的上一级目录

//例如:
include "./test2.php";
require "../../test3.html";
Copy after login

Absolute path:

is divided into local absolute path and network absolute path

Local absolute path:

Search recursively from the local root directory layer by layer until you find the file to be imported in the corresponding directory.

include "C:/PHP/test/test2.php";
Copy after login

We all know that absolute paths are not conducive to the portability and maintainability of the project, so it is generally rare to write absolute paths directly in the code, but what should we do if we need to use absolute paths? ? There are magic constants __DIR__ and global array $_SERVER in PHP. The usage is as follows:

<?php
define(&#39;DS&#39;) or define(&#39;DS&#39;,DIRECTORY_SEPARATOR);

echo "使用绝对路径引入(方法一)";
include __DIR__ . DS . &#39;test2.php&#39;;

echo "使用绝对路径载入方法(方法二)";
$root = $_SERVER[&#39;DOCUMENT_ROOT&#39;]; // 获得当前站点的根目录
include $root.DS.&#39;node_test&#39;.DS.&#39;inAndRe&#39;.DS. &#39;test2.php&#39;;
?>
Copy after login

Absolute network path:

Link to the file through the URL, and the server will The file pointed to by the URL will be returned after execution

include "http://www.lishnli/index.php"
Copy after login

No path:

Only the file name is given but no path information is given. At this time, PHP will be in the current web page directory. Search for the file. If a file with the same name is found, execute it and import it.

需要注意:无论采用哪种路径,必须要加上文件后缀名,这四种文件载入方式不能识别无后缀的文件。

//test1.php
include "./test2.php";
//结果:this is test2


//test1.php
include "./test2";
//结果:
Copy after login

返回值的比较

上文说道include有返回值,而require无返回值

对于include,如果载入成功,有返回值,返回值为1;如果载入失败,则返回false.

对于require,如果载入成功,有返回值,返回值为1;如果载入失败,无返回值。

//test1.php
<?php

$a = include "./test2.php";
var_dump($a);
echo "<br>";

$b = include "./test2.phps";
var_dump($b);
echo "<br>";

$c = require "./test2.php";
var_dump($c);
echo "<br>";

$d = require "./test2.phps";
var_dump($d);

?>
Copy after login

输出:

What are the ways to import files in PHP? Introduction to four methods of introducing files in PHP (code)

当文件中有return:

当被载入文件中有return语句时,会有另外的机制,此时return语句的作用是终止载入过程,即被载入文件中return语句的后续代码不再载入。return语句也可以用于被载入文件载入时返回一个数据。

//test1.php
<?php
$a = include "./test2.php";
echo "<br>";
var_dump($a);
?>


//test2.php
//该文件中有return语句
<?php
$b = &#39;test2&#39;;
echo "被载入的文件:A 位置";
return $b;
echo "<br 被载入的文件: B 位置";
?>
Copy after login

结果:

相关推荐:

php引入css文件出错,但是网页已经有样式了

php 字符串写入文件或追加入文件(file_put_contents)

The above is the detailed content of What are the ways to import files in PHP? Introduction to four methods of introducing files in PHP (code). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles