Home Backend Development PHP Tutorial php--require/include/require_once/include_once

php--require/include/require_once/include_once

Nov 24, 2016 am 09:12 AM
include include_once php require require_once

require

require and include are almost identical, except for the way failure is handled. require generates an E_COMPILE_ERROR level error when an error occurs. In other words, it will cause the script to terminate while include only generates a warning (E_WARNING) and the script will continue to run.

include

include statement includes and runs the specified file.

The following documents also apply to require:

The included file is first searched according to the path given by the parameter. If no directory (only the file name) is given, it is searched according to the directory specified by include_path. If the file is not found under include_path, include will finally search in the directory where the calling script file is located and the current working directory. The include structure will issue a warning if the file is not found at the end; this is different from require, which will issue a fatal error. (For include_path, please refer to this article: PHP extension options and configuration information)

If the path is defined - whether it is an absolute path (starting with a drive letter or under Windows, starting with / under Unix/Linux) or the current Relative paths to directories (starting with . or .. ) - include_path are completely ignored. For example, if a file begins with ../, the parser will look for the file in the parent directory of the current directory.

When a file is included, the code contained in it inherits the variable scope of the include line. From that point on, any variables available in the calling file at that line are also available in the called file. However, all functions and classes defined in include files have global scope.

Example #1 Basic include example

1

2

3

4

5

6

7

8

9

10

11

vars.php

<?php

    $color = &#39;green&#39;;

    $fruit = &#39;apple&#39;;

?>

test.php

<?php

    echo "A $color $fruit"; // A

    include &#39;vars.php&#39;;

    echo "A $color $fruit"; // A green apple

?>

Copy after login

If include appears in a function in a calling file, all code contained in the called file will behave as if they were defined inside the function. So it will follow the variable scope of that function. The one exception to this rule is magic constants, which are processed by the parser before inclusion occurs.

Example #2 Includes in function

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<?php

function foo()

{

    global $color;

    include &#39;vars.php&#39;;

    echo "A $color $fruit";

}

/* vars.php is in the scope of foo() so *

* $fruit is NOT available outside of this *

* scope. $color is because we declared it *

* as global. */

foo(); // A green apple

echo "A $color $fruit"; // A green

?>

Copy after login

When a file is included, the parser leaves PHP mode at the beginning of the target file and enters HTML mode, and resumes at the end of the file. For this reason, any code in an object file that needs to be executed as PHP code must be included within valid PHP start and end tags.

If "URL fopen wrappers" are enabled in PHP (the default configuration), it is possible to specify URLs (via HTTP or other supported wrapping protocols - see Supported Protocols and Wrapping Protocols) instead of local files to be included. document. If the target server interprets the target file as PHP code, you can pass variables to the included file using the URL request string for HTTP GET. This is not strictly the same thing as containing a file and inheriting the variable space of the parent file; the script file has actually been run on the remote server, and the local script includes its results.

Warning The Windows version of PHP before version 4.3.0 does not support accessing remote files through this function, even if allow_url_fopen is enabled.

Example #3 include via HTTP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<?php

    /* This example assumes that www.example.com is configured to parse .php *

     * files and not .txt files. Also, &#39;Works&#39; here means that the variables *

     * $foo and $bar are available within the included file. */

    // Won&#39;t work; file.txt wasn&#39;t handled by www.example.com as PHP

    include &#39;http://www.example.com/file.txt?foo=1&bar=2&#39;;

    // Won&#39;t work; looks for a file named &#39;file.php?foo=1&bar=2&#39; on the

    // local filesystem.

    include &#39;file.php?foo=1&bar=2&#39;;

    // Works.

    include &#39;http://www.example.com/file.php?foo=1&bar=2&#39;;

    $foo = 1;

    $bar = 2;

    include &#39;file.txt&#39;; // Works.

    include &#39;file.php&#39;; // Works.

?>

Copy after login

Security warning

Remote files may go through the remote server processing (depending on the file suffix and whether the remote server is running PHP), but a valid PHP script must be generated because it will be processed by the local server. If a file from a remote server should be run remotely and only output the results, it is better to use the readfile() function. Also take extra care to ensure that remote scripts produce legal and required code.

Handling return values: include returns FALSE and issues a warning on failure. A successful include returns 1 unless otherwise specified in the include file. You can use the return statement in an included file to terminate the execution of the program in the file and return to the script that called it. It is also possible to return values ​​from included files. The return value of the include call can be obtained like a normal function. This does not work when including a remote file, however, unless the remote file's output has legal PHP start and end tags (like any local file). You can define the required variables within the tag, which will be available after the location where the file is included.

Because include is a special language structure, its parameters do not require parentheses. Be careful when comparing their return values.

Example #4 比较 include 的返回值

1

2

3

4

5

6

7

8

9

10

<?php

// won&#39;t work, evaluated as include((&#39;vars.php&#39;) == &#39;OK&#39;), i.e. include(&#39;&#39;)

if (include(&#39;vars.php&#39;) == &#39;OK&#39;) {

    echo &#39;OK&#39;;

}

// works

if ((include &#39;vars.php&#39;) == &#39;OK&#39;) {

    echo &#39;OK&#39;;

}

?>

Copy after login

Example #5 include 和 return 语句

return.php

$var = 'PHP';

return $var;

?>

noreturn.php

$var = 'PHP';

?>

testreturns.php

$foo = include 'return.php';

echo $foo; // prints 'PHP'

$bar = include 'noreturn.php';

echo $bar; // prints 1

?>

$bar 的值为 1 是因为 include 成功运行了。注意以上例子中的区别。第一个在被包含的文件中用了 return 而另一个没有。如果文件不能被包含,则返回 FALSE 并发出一个E_WARNING 警告。

如果在包含文件中定义有函数,这些函数不管是在 return 之前还是之后定义的,都可以独立在主文件中使用。如果文件被包含两次,PHP 5 发出致命错误因为函数已经被定义,但是 PHP 4 不会对在 return 之后定义的函数报错。推荐使用 include_once 而不是检查文件是否已包含并在包含文件中有条件返回。

另一个将 PHP 文件“包含”到一个变量中的方法是用输出控制函数结合 include 来捕获其输出,例如:

Example #6 使用输出缓冲来将 PHP 文件包含入一个字符串

1

2

3

4

5

6

7

8

9

10

11

12

13

<?php

$string = get_include_contents(&#39;somefile.php&#39;);

function get_include_contents($filename) {

    if (is_file($filename)) {

        ob_start();

        include $filename;

        $contents = ob_get_contents();

        ob_end_clean();

        return $contents;

    }

    return false;

}

?>

Copy after login

要在脚本中自动包含文件,参见 php.ini 中的 auto_prepend_file 和 auto_append_file 配置选项。

Note: 因为是一个语言构造器而不是一个函数,不能被 可变函数 调用。

require_once

(PHP 4, PHP 5)

require_once 语句和 require 语句完全相同,唯一区别是 PHP 会检查该文件是否已经被包含过,如果是则不会再次包含

include_once

(PHP 4, PHP 5)

include_once 语句在脚本执行期间包含并运行指定文件。此行为和 include 语句类似,唯一区别是如果该文件中已经被包含过,则不会再次包含。如同此语句名字暗示的那样,只会包含一次。

include_once 可以用于在脚本执行期间同一个文件有可能被包含超过一次的情况下,想确保它只被包含一次以避免函数重定义,变量重新赋值等问题。

Note:

在 PHP 4中,_once 的行为在不区分大小写字母的操作系统(例如 Windows)中有所不同,例如:

Example #1 include_once 在 PHP 4 运行于不区分大小写的操作系统中

1

2

3

4

<?php

include_once "a.php"; // 这将包含 a.php

include_once "A.php"; // 这将再次包含 a.php!(仅 PHP 4)

?>

Copy after login

 

此行为在 PHP 5 中改了,例如在 Windows 中路径先被规格化,因此 C:\PROGRA~1\A.php 和 C:\Program Files\a.php 的实现一样,文件只会被包含一次。


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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1280
29
C# Tutorial
1257
24
What happens if session_start() is called multiple times? What happens if session_start() is called multiple times? Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

The Compatibility of IIS and PHP: A Deep Dive The Compatibility of IIS and PHP: A Deep Dive Apr 22, 2025 am 12:01 AM

IIS and PHP are compatible and are implemented through FastCGI. 1.IIS forwards the .php file request to the FastCGI module through the configuration file. 2. The FastCGI module starts the PHP process to process requests to improve performance and stability. 3. In actual applications, you need to pay attention to configuration details, error debugging and performance optimization.

What is the significance of the session_start() function? What is the significance of the session_start() function? May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

Composer: Aiding PHP Development Through AI Composer: Aiding PHP Development Through AI Apr 29, 2025 am 12:27 AM

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

PHP and IIS: Making Them Work Together PHP and IIS: Making Them Work Together Apr 21, 2025 am 12:06 AM

Configuring and running PHP on IIS requires the following steps: 1) Download and install PHP, 2) Configuring IIS and adding FastCGI module, 3) Create and set up an application pool, 4) Create a website and bind to an application pool. Through these steps, you can easily deploy PHP applications on your Windows server and improve application stability and efficiency by configuring scaling and optimizing performance.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

H5: Key Improvements in HTML5 H5: Key Improvements in HTML5 Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

Composer: The Package Manager for PHP Developers Composer: The Package Manager for PHP Developers May 02, 2025 am 12:23 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json file. 1) parse composer.json to obtain dependency information; 2) parse dependencies to form a dependency tree; 3) download and install dependencies from Packagist to the vendor directory; 4) generate composer.lock file to lock the dependency version to ensure team consistency and project maintainability.

See all articles