Bear in mind that require_once doesn't have a return value (neither does require; since they both halt execution on failure), so this won't work:
<?
require_once("path/to/myfile.php") or die("Couldn't load myfile");
?>
because you will get a very unhelpful error:
PHP Fatal error: require_once() : Failed opening required '1' (include_path='.;C:\\php5\\pear') in C:\path\to\code.php on line 1
This was mentioned on the php-general mailing list in about 2003 but is a gotcha I have seen a few people come across. If you want to check to see if a file was included, use @include() instead.
require_once()
require_once()문은 스크립트 수행기간 중에 특정파일을 인클루드하고 적용시킨다. 이것은 require()문과 비슷하게 동작한다. 오직 파일의 코드가 이미 인클루드되었다면 다시 인클루드되지 않을것 이라는 차이점이 있다. 이 구문이 어떻게 작용하는지에 대한 정보를 알아보려면 require()함수에 대한 문서를 보세요.
require_once()는 특정 스크립트 수행기간동안 한번이상 인클루드되고 적용될수 있는 상황에서 사용하도록 한다. 그리고 함수 중복 정의와 변수값 중복 지정 등에 대한 문제를 회피하기 위해서는 정확히 한번 인클루드될 필요가 있을것이다.
require_once()과 include_once()의 사용예는 최신 PHP 소스코드 안에 포함된 » PEAR코드를 참고할것.
반환값은 include()와 동일합니다. 파일이 이미 포함되었면, TRUE를 반환합니다.
Note: require_once()는 PHP 4.0.1에 추가되었다.
Note: require_once()와 include_once()은 대소문자를 구별하지 않는 운영체제(윈도우 같은)에서는 기대하던대로 동작하지 않을지 모른다.
이 동작은 PHP 5에서 바뀌었습니다 - 경로가 먼저 표준화되기 때문에 C:\PROGRA~1\A.php은 C:\Program Files\a.php와 동일하게 인식하고, 파일은 딱 한번만 포함하게 됩니다.Example#1 require_once()는 윈도우에서 대소문자를 구별하지 못합니다.
<?php
require_once("a.php"); // a.php를 포함합니다.
require_once("A.php"); // 윈도우에서 또다시 a.php를 포함합니다. (PHP 4만)
?>
PHP 4.3.0 이후의 Windows 버전 PHP에서는 이 함수를 이용하여 원격 파일에 접근할 수 없습니다. allow_url_fopen을 활성화하여도 마찬가지입니다.
참고: require(), include(), include_once(), get_required_files(), get_included_files(), readfile(), virtual().
require_once
14-Mar-2008 04:20
11-Feb-2008 07:00
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().
20-Aug-2007 10:33
Beware: As miqrogroove said below, require_once() is not independent of require() -- but vice versa, require() IS independent of require_once()!
Let's turn miqrogroove's example around:
echo.php
<?php
echo "42!<br />\n";
?>
test.php
<?php
require_once 'echo.php';
require 'echo.php';
// 42!
// 42!
?>
So: require_once() will NOT include a file previously included by require(), while require WILL include a file previously included by require_once.
14-Jun-2007 02:02
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.
07-Mar-2007 11:22
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%.
19-Jan-2007 12:00
<?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.
01-Sep-2006 02:28
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.
10-Mar-2006 07:13
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.
24-Feb-2006 11:00
How to use Require_Once with error reporting to include a MySQL Connection file:
-------------------------------------------------------------------
$MySQLConnectFile = './inc/MySQL.Class.php';
if ( is_dir ( './inc/' ) )
{
$IncIsDir == TRUE;
}
if ( file_exists ( $MySQLConnectFile ) )
{
$MySQLFileExists == TRUE;
}
if ( $IncIsDir && $MySQLFileExists )
{
require_once ( $MySQLConnectFile )
}
else
{
echo '<b>Error:</b> <i>Could not read the MySQL Connection File. Please try again later.';
exit();
}
----------------------------------------------------------------------
05-Dec-2005 07:12
@georg_gruber at yahoo dot com
Files for including are first looked in include_path relative to the current working directory and then in include_path relative to the directory of current script. E.g. if your include_path is ., current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/ and then in /www/include/. If filename begins with ./ or ../, it is looked only in include_path relative to the current working directory.
Taken from http://us2.php.net/manual/en/function.include.php
06-Oct-2005 03:06
A very interesting behaviour of require_once (and probably all include commands):
consider the following files:
/index.php -> require_once('/inc/library.php');
/function1.php -> print('/function1.php');
/inc/library.php -> require_once('function1.php');
/inc/function1.php -> print('/inc/function1.php');
Note that /function1.php and /inc/function1.php are files with the SAME filename in different folders.
If you "/index.php" is executed it will output
"/function1.php".
Although /index.php "includes" /inc/library.php the scope of the file is still /index.php therefor /function1.php will be found even it could be asumed the /inc/function1.php is the correct one.
And it gets more interesting: if you delete /function1.php and execute /index.php PHP checks this and "includes" /inc/function1.php.
01-May-2005 11:10
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
22-Mar-2005 05:38
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.
17-Mar-2005 02:19
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")
10-Mar-2005 05:00
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
21-Jan-2005 02:00
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.
> 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.
