Home  >  Article  >  Backend Development  >  php--require/include/require_once/include_once

php--require/include/require_once/include_once

伊谢尔伦
伊谢尔伦Original
2016-11-24 09:12:041329browse

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

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
?>

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

<?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
?>

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

<?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.
?>

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 的返回值

<?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;;
}
?>

Example #5 include 和 return 语句

return.php
5e761dc189df02af8b3a77896bf6f89f

noreturn.php
ebe9369892d7384cf276f620b752f65d

testreturns.php
3f955376bfdcb5b15a5de19c4f63fc0f

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

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

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

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

<?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;
}
?>

要在脚本中自动包含文件,参见 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 运行于不区分大小写的操作系统中

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

 

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


Statement:
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