略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: require_once

2024-11-22

require_once

(PHP 4, PHP 5, PHP 7, PHP 8)

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

参见 include_once 的文档来理解 _once 的含义,并理解与没有 _once 时候有什么不同。

add a noteadd a note

User Contributed Notes 26 notes

up
165
bimal at sanjaal dot com
11 years ago
If your code is running on multiple servers with different environments (locations from where your scripts run) the following idea may be useful to you:

a. Do not give absolute path to include files on your server.
b. Dynamically calculate the full path (absolute path)

Hints:
Use a combination of dirname(__FILE__) and subsequent calls to itself until you reach to the home of your '/index.php'. Then, attach this variable (that contains the path) to your included files.

One of my typical example is:

<?php
define
('__ROOT__', dirname(dirname(__FILE__)));
require_once(
__ROOT__.'/config.php');
?>

instead of:
<?php require_once('/var/www/public_html/config.php'); ?>

After this, if you copy paste your codes to another servers, it will still run, without requiring any further re-configurations.

[EDIT BY danbrown AT php DOT net: Contains a typofix (missing ')') provided by 'JoeB' on 09-JUN-2011.]
up
9
boda0128318 at gmail dot com
1 year ago
1 - "require" and "require_once"  throw a fatal error if the file is not
       existing  and stop the script execution

2 - "include" and "include_once" throw a warning and the execution
       continues

3 - "require_once" and "include_once" as their names suggests ,
      they will not include the file if the file was already included with
      "require", "require_once", "include" or "include_once"

try the following code:

create a file called "index.php"

<?php

require "first.php"// this will include the file

include_once "first.php"// this will not as it was included using "require"

require_once "first.php"// this will not as it was included using "require"

?>

and another file that is called "first.php" and write the following header

-------------------------------

<h1>Hello every one</h1>

--------------------------------

i hope this will help you
up
8
powtac at gmx dot de
6 years ago
"require_once" and "require" are language constructs and not functions. Therefore they should be written without "()" brackets!
up
0
bobray99 at softville dot com
1 month ago
Be careful when using include_once and require_once for files that return a value:

fiddle2.php
<?php
return "Some String";

fiddle.php
<?php
$s
= require_once('fiddle2.php');
echo
"\n" . $s;
$s = require_once('fiddle2.php');
echo
"\n" . $s;

/* output 
Some String
1
*/

The second time require_once occurs, it returns 1 because the file has already been included.
up
-3
apis17
4 years ago
require_once may not work correctly inside repetitive function when storing variable for example:

file: var.php
<?php
$foo
= 'bar';
?>

file: check.php
<?php

function foo(){
    require_once(
'var.php');
    return
$foo;
}

for(
$a=1;$a<=5;$a++){
    echo
foo()."<br>";
}

>
php check.php
result
:
bar
<empty line>
<empty
line>
<empty
line>
<empty
line>

to make sure variable bar available at each function call, replace require once with require. eg situation: https://stackoverflow.com/questions/29898199/variables-not-defined-inside-function-on-second-time-at-foreach

Solution:

file: check2.php
<?php

function foo(){
    require(
'var.php');
    return
$foo;
}

for(
$a=1;$a<=5;$a++){
    echo
foo()."<br>";
}

>
php check2.php
result
:
bar
bar
bar
bar
bar
up
-36
Konstantin Rozinov (krozinov[at]gmail)
13 years ago
There's been a lot of discussion about the speed differences between using require_once() vs. require().
I was curious myself, so I ran some tests to see what's faster:
- require_once() vs require()
- using relative_path vs absolute_path

I also included results from strace for the number of stat() system calls.  My results and conclusions below.

METHODOLOGY:
------------
The script (test.php):
<?php
$start_time
= microtime(true);
   
/*
  * Uncomment one at a time and run test below.
  * sql_servers.inc only contains define() statements.
  */

//require ('/www/includes/example.com/code/conf/sql_servers.inc');
//require ('../../includes/example.com/code/conf/sql_servers.inc');
//require_once ('/www/includes/example.com/code/conf/sql_servers.inc');
//require_once ('../../includes/example.com/code/conf/sql_servers.inc');

$end_time = microtime(true);

$handle = fopen("/tmp/results", "ab+");
fwrite($handle, ($end_time - $start_time) . "\n");
fclose($handle);
?>

The test:
  I ran ab on the test.php script with a different require*() uncommented each time:
  ab -n 1000 -c 10 www.example.com/test.php

RESULTS:
--------
The average time it took to run test.php once:
require('absolute_path'):      0.000830569960420
require('relative_path'):      0.000829198306664
require_once('absolute_path'): 0.000832904849136
require_once('relative_path'): 0.000824960252097

The average was computed by eliminating the 100 slowest and 100 fastest times, so a total of 800 (1000 - 200) times were used to compute the average time.  This was done to eliminate any unusual spikes or dips.

The question of how many stat() system calls were made can be answered as follows:
- If you run httpd -X and then do an strace -p <pid_of_httpd>, you can view the system calls that take place to process the request.
- The most important thing to note is if you run test.php continuously (as the ab test does above), the stat() calls only happen for the first request:

  first call to test.php (above):
  -------------------------------
  lstat64 ("/www", {st_mode=S_IFDIR|0755, st_size=...
  lstat64 ("/www/includes", {st_mode=S_IFDIR|0755,...
  lstat64 ("/www/includes/example.com", {st_mode=S...
  lstat64 ("/www/includes/example.com/code", {st_m...
  lstat64 ("/www/includes/example.com/code/conf", ...
  lstat64 ("/www/includes/example.com/code/conf/sql_servers.inc", {st_mode...
  open ("/www/includes/example.com/code/conf/sql_servers.inc", O_RDONLY) = 17
 
  subsequent calls to test.php:
  -----------------------------
  open ("/www/includes/example.com/code/conf/sql_servers.inc", O_RDONLY) = 17

- The lack of stat() system calls in the subsequent calls to test.php only happens when test.php is called continusly.  If you wait a certain period of time (about 1 minute or so), the stat() calls will happen again.
- This indicates that either the OS (Ubuntu Linux in my case), or Apache is "caching" or knows the results of the previous stat() calls, so it doesn't bother repeating them.
- When using absolute_path there are fewer stat() system calls.
- When using relative_path there are more stat() system calls because it has to start stat()ing from the current directory back up to / and then to the include/ directory.

CONCLUSIONS:
------------
- Try to use absolute_path when calling require*().
- The time difference between require_once() vs. require() is so tiny, it's almost always insignificant in terms of performance.  The one exception is if you have a very large application that has hundreds of require*() calls.
- When using APC opcode caching, the speed difference between the two is completely irrelevant.
- Use an opcode cache, like APC!

Konstantin Rozinov
krozinov [at] gmail
up
-43
miqrogroove
17 years ago
require_once() is NOT independent of require().  Therefore, the following code will work as expected:

echo.php
<?php
echo "Hello";
?>

test.php
<?php
require('echo.php');
require_once(
'echo.php');
?>

test.php outputs: "Hello".

Enjoy,
-- Miqro
up
-12
Mental_Wanderer
3 years ago
Friendly reminder about namespaces...
Including or requiring a PHP file that defines as namespace means that the namespace name (or its "use ... as ..." alias) is always necessary to make use of the included file's content:

// A.php

<?php namespace A_NAMESPACE;

   function
foo()
   {
     
// What foo does...
  
}
?>

// B.php

<?php
  
require_once( 'A.php' );
   use \
A_NAMESPACE as common;

  
common\foo(); // Does that foo thing...

  
foo();  // Fatal Error...
?>
up
-42
Dodo
7 years ago
If you happen to encounter some "Warning: require_once(): failed to open stream" and you are certain the provided path is right, consider the following example & solution.

Considering the following tree:
+ C:\server\absolute\path\
    + somefolder\
        - index.php
    + supbath
        + anotherfolder1\
            - file1.php
            - file2.php
        + anotherfolder2\
            - file3.php

With the respective sources:
original index.php:
<?php

   
// absolute path
    // inclusion status: SUCCESS
   
require_once 'C:\server\absolute\path\subpath\anotherfolder1\file1.php';

?>

original file1.php:
<?php

   
// relative path
    // inclusion status: SUCCESS
   
require_once 'file2.php';

   
// relative path
    // inclusion status: FAILURE
   
require_once '../anotherfolder2/file3.php';

?>

You will notice the use of "\" as DIRECTORY_SEPARATOR, but the same result is obtained using "/".
Assumption ? PHP does not behave as it should if it encounters a relative path starting by a '../'. Well, this is not true.

Below is a modified file1.php:
<?php

   
// absolute path
    // inclusion status: SUCCESS
   
require_once '/file2.php';

   
// absolute path
    // inclusion status: SUCCESS
   
require_once '/../anotherfolder2/file3.php';

?>

It seems that PHP recognizes a non-prefixed file name as an absolute path in a require_once, and that it computes this absolute path from a relative context.

I am not sure this is the expected behaviour, but it was quite hard to figure out. Also, if you want to recognize those special cases where you had to specify a relative path starting with a "/", you can use the following trick.

<?php

   
// it goes down one level, and then goes up one level : the result is neutral, but after prefixing your paths with this, PHP handles them
   
define ('REQUIRE_TRICK', '/TRICK/../');

    require_once
REQUIRE_TRICK . 'file2.php';
    require_once
REQUIRE_TRICK . '../anotherfolder2/file3.php';

?>

If this ever gets reworked/fixed, it will be easy to remove the define.
up
-22
ivan[DOT_NO_SPAM]chepurnyi[AT]gmail
12 years ago
Also if you have a large MVC framework, it make sense to compile  structure "file/path/to/class.php" to something like this "file_path_to_class.php", it will speed up any type of php files includes, becouse php interpreter will not check FS stat data for directories "file", "file/path", "file/path/to", etc.
up
-20
inci szlk
7 years ago
you can also use this type define to get exact path of root directory. So, it won't mess if the file is in whatever directory in whatever directory.

if (!defined("DOCUMENT_ROOT")) define("DOCUMENT_ROOT", $_SERVER['DOCUMENT_ROOT']);

require_once DOCUMENT_ROOT.'/hello/world.php';
up
-24
thomas dot revell at uwe dot ac dot uk
17 years ago
Regarding the case insensitivity problems on Windows, it looks to me as though it is a problem in PHP5 as well (at least in some cases).

The following gave me problems:

From file URLSwitcher.php
<?php
require_once 'slimError/slimError.php';
require_once
'Navigator_Cache.php';
....
?>

From file Navigator_Cache.php
<?php
require_once 'slimError/slimerror.php';
...
?>

From file slimerror.php
<?php
class SLIMError {
...
}
?>
The above setup gave me an error : "Cannot redeclare class SLIMError"

If I change the require_once in URLSwitcher.php to match the one in Navigator_Cache.php, there isn't a problem, but if I do this the other way round, the same problem occurs.
up
-31
jazfresh at hotmail.com
15 years ago
Check how many files you are including with get_required_files(). If it's a significant number (> 100), it may be worth "compiling" the main PHP file. By "compiling", I mean write a script that reads a PHP file and replaces any "include/require_once" references with either:
- the file that it's requiring
- a blank line if that file has been included before

This function can be recursive, thus building up a large PHP file with no require_once references at all. The speedup can be dramatic. On one of our pages that included 115 classes, the page was sped up by 60%.
up
-33
jason semko at gmail dot com
11 years ago
If you are coding on localhost and require_once is not opening files due to 'relative paths' a simple solution is:

<?php

     
require_once(dirname(__FILE__) . "/file.php");

?>

If you have file.php under the folder 'includes' (or anywhere for that matter), then folder 'public' AND folder 'public/admin' will be able to access all required files despite having different relative paths.
up
-23
antoine dot pouch at mcgill dot ca
16 years ago
require_once (and include_once for that matters) is slow.
Furthermore, if you plan on using unit tests and mock objects (i.e. including mock classes before the real ones are included in the class you want to test), it will not work as require() loads a file and not a class.

To bypass that, and gain speed, I use :

<?php
class_exists
('myClass') || require('path/to/myClass.class.php');
?>

I tried to time 100 require_once on the same file and it took the script 0.0026 seconds to run, whereas with my method it took only 0.00054 seconds. 4 times faster ! OK, my method of testing is quite empirical and YMMV but the bonus is the ability to use mock objects in your unit tests.
up
-24
amcewen at look dot ca
14 years ago
Perhaps it would be clearer to say that require_once() includes AND evaluates the resulting code once.  More specifically, if there is code in the script file other than function declarations, this code will only be executed once via require_once().
up
-29
spark at limao dot com dot br
11 years ago
if you use require_once on a file A pointing to file B, and require_once in the file B pointing to file A, in some configurations you will get stuck

also wouldn't it be nice to manage that to prevent getting stuck AND use the good old Java import?

<?php
      
function import($path=""){
               if(
$path == ""){ //no parameter returns the file import info tree;
                      
$report = $_SESSION['imports'];
                       foreach(
$report as &$item) $item = array_flip($item);
                       return
$report;
               }

              
$current = str_replace("\\","/",getcwd())."/";
              
$path = $current.str_replace(".","/",$path);
               if(
substr($path,-1) != "*") $path .= ".class.php";

              
$imports = &$_SESSION['imports'];
               if(!
is_array($imports)) $imports = array();

              
$control = &$imports[$_SERVER['SCRIPT_FILENAME']];
               if(!
is_array($control)) $control = array();

               foreach(
glob($path) as $file){
                      
$file = str_replace($current,"",$file);
                       if(
is_dir($file)) import($file.".*");
                       if(
substr($file,-10) != ".class.php") continue;
                       if(
$control[$file]) continue;
                      
$control[$file] = count($control);
                       require_once(
$file);
               }
       }
?>

just remember to start the session and to enable the glob function

now you can use
<?php
    import
("package.ClassName");
   
import("another.package.*"); //this will import everything in the folder
?>
up
-25
acholoc at gmail dot com
8 years ago
I think it's important (at least for beginners) to mention somewhere clearly visible that require_once, when being used in a class, cannot be outside a function. (I am aware that even this, i.e. using it within the function is bad practice). However, that information could have saved me some valuable time troubleshooting the "unexpected T_REQUIRE_ONCE" error.
up
-34
Anonymous
18 years ago
> Mac OS X systems are also not case-sensitive.
That depends on the filesystem:
- HFS and HFS+ are NOT case sensitive.
- UFS is case sensitive.
up
-27
info at erpplaza dot com
11 years ago
Include all files from a particular directory

<?php
foreach (glob("classes/*.php") as $filename)
{
    include
$filename;
}
?>

ERPPlaza
up
-26
rejjn at mail dot nu
15 years ago
The following only applies to case insensitive systems like Windows.

Even though the documentation sais that "the path is normalized" that doesn't seem to be true in all cases.

If you are using the magic __autoload() function (or if the framework you're using is using it) and it includes the requested class file with complete path or if you override the include path in mid execution, you may have some very strange behavior. The most subtle problem is that the *_once functions seem to differentiate between c:\.... and C:\....

So to avoid any strange problems and painfull debugging make sure ALL paths you use within the system have the same case everywhere, and that they correspond with the actual case of the filesystem. That includes include paths set in webserver config/php.ini, auto load config, runtime include path settings or anywhere else.
up
-31
manuel schaffner
15 years ago
The path for nested require_once() is always evaluated relative to the called / first file containing require_once(). To make it more flexible, maintain the include_path (php.ini) or use set_include_path() - then the file will be looked up in all these locations.
up
-28
Pure-PHP
17 years ago
require_once can slower your app, if you include to many files.

You cann use this wrapper class, it is faster than include_once

http://www.pure-php.de/node/19

require_once("includeWrapper.class.php")

includeWrapper::require_once("Class1.class.php");
includeWrapper::require_once("Class1.class.php");
includeWrapper::require_once("Class2.class.php")
up
-28
ulderico at maber dot com dot br
17 years ago
With both of your functions guys, Pure-PHP and jtaal at eljakim dot nl, you'll not have any variables available GLOBALly if they're supposed to be globals...

That's why my import handles better those situation. OK, SOME MAY DISPUTE that using include_once and require_once may slow down an application. But what's the use to do IN PHP what the interpreter *should* do better for you. Thusly these workarounds shall, some time in the future, DIE.

Thus It's better to well design your application to keep some order using few INCLUDES and REQUIRES in it rather than insert MANY AND SEVERAL *_once around.
up
-29
sneskid at hotmail dot com
15 years ago
<?php
function & rel($r, &$f) {return file_exists( ( $f = ( dirname($r).'/'.$f ) ) );}
function &
relf($r, $f) {return rel($r,$f) ? file_get_contents($f) : null;}
function &
reli($r, $f) {return rel($r,$f) ? include($f) : null;}
function &
relr($r, $f) {return rel($r,$f) ? require($f) : null;}
function &
relio($r, $f) {return rel($r,$f) ? include_once($f) : null;}
function &
relro($r, $f) {return rel($r,$f) ? require_once($f) : null;}
?>

I found it useful to have a function that can load a file relative to the calling script and return null if the file did not exist, without raising errors.

<?php
/*
Load file contents or return blank if it's not there.
Relative to the file calling the function.
*/
echo relf(__FILE__, 'some.file');
?>

It was easy to modify and just as useful for require/include.

<?php
/*
Require the file once.
It's like suppressing error messages with @ but only when the file does not exist.
Still shows compile errors/warning, unless you use @relro().
Relative to the file calling the function.
*/
relro(__FILE__, 'stats.php');
?>

If you work with a deep php file structure and a barrage of includes/requires/file-loads this works well.
up
-34
jtaal at eljakim dot nl
17 years ago
When you feel the need for a require_once_wildcard function, here's the solution:

<?php // /var/www/app/system/include.inc.php

function require_once_wildcard($wildcard, $__FILE__) {
 
preg_match("/^(.+)\/[^\/]+$/", $__FILE__, $matches);
 
$ls = `ls $matches[1]/$wildcard`;
 
$ls = explode("\n", $ls);
 
array_pop($ls); // remove empty line ls always prints
 
foreach ($ls as $inc) {
    require_once(
$inc);
  }
}

?>

The $__FILE__ variable should be filled with the special PHP construct __FILE__:
<?php // /var/www/app/classes.inc.php

require_once('system/include.inc.php');
require_once_wildcard("classes/*.inc.php", __FILE__);

?>

The (*.inc.php) files inside the directory classes are automagically included using require_once_wildcard.

This solution may not be as useful when using PHP5 in combination with classes and the autoload feature.

--
Jaap Taal

官方地址:https://www.php.net/manual/en/function.require-once.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3