SunshinePHP Developer Conference 2015

include_once

(PHP 4, PHP 5)

include_once 命令は、スクリプトの実行時に指定 したファイルを読み込み評価します。この動作は、 include 命令と似ていますが、ファイルからのコー ドが既に読み込まれている場合は、再度読み込まれないという重要な違い があります。その名が示す通り、ファイルは一度しか読み込まれません。

include_once は、スクリプトの実行時に同じファイ ルが複数回読み込まれ、評価される可能性がある場合に、関数の再定義や 変数値の再代入といった問題を回避するために一回だけ読み込ませるため に使用します。

この関数の動作についての情報は include のドキュメントを参照ください。

注意:

PHP 4 では、大文字小文字を区別しない OS (Windows など) では _once の動作が多少異なります。次に例を示します。

例1 PHP 4 における、大文字小文字を区別しない OS 上での include_once

<?php
include_once "a.php"// a.phpを読み込みます
include_once "A.php"// これもa.phpを読み込みます! (PHP 4 のみ)
?>
この挙動は PHP 5 で変更されました。たとえば Windows ではまず最初にパスが正規化され、 C:\PROGRA~1\A.phpC:\Program Files\a.php と同じ扱いとなります。 ファイルは一度だけ読み込まれるようになります。

add a note add a note

User Contributed Notes 5 notes

up
52
roach dot scott+spam at googlemail dot com
6 years ago
If you include a file that does not exist with include_once, the return result will be false.

If you try to include that same file again with include_once the return value will be true.

Example:
<?php
var_dump
(include_once 'fakefile.ext'); // bool(false)
var_dump(include_once 'fakefile.ext'); // bool(true)
?>

This is because according to php the file was already included once (even though it does not exist).
up
-4
emanuele at rogledi dot com
6 years ago
For include_once a file in every paths of application we can do simply this

include_once($_SERVER["DOCUMENT_ROOT"] . "mypath/my2ndpath/myfile.php");
up
-5
flobee at gmail dot com
9 years ago
i already had a discussion with several people about "not shown errors"
error reporting and all others in php.ini set to: "show errors" to find problems:
the answer i finally found:
if you have an "@include..." instead of "include..." or "require..('somthing') in any place in your code
all following errors are not shown too!!!

so, this is actually a bad idea when developing because paser errors will be droped too:
<?php
if(!@include_once('./somthing') ) {
    echo
'can not include';
}
?>

solution:
<?php
if(!@file_exists('./somthing') ) {
    echo
'can not include';
} else {
   include(
'./something');
}
?>
up
-9
webmaster AT domaene - kempten DOT de
8 years ago
Since I like to reuse a lot of code it came handy to me to begin some sort of library that I stored in a subdir
e.g. "lib"

The only thing that bothered me for some time was that although everything worked all IDEs reported during editing
these useless warnings "file not found" when library files included other library files, since my path were given all relative to the corresponding document-root.

Here is a short workaround that makes that gone:

<?php
// Change to your path

if(strpos(__FILE__,'/lib/') != FALSE){
   
chdir("..");
}
include_once (
'./lib/other_lib.inc');
// ... or any other include[_once] / require[_once]
?>

just adjust the path and it will be fine - also for your IDE.

greetings
up
-10
Anonymous
11 days ago
farooq

af
sdf
dsf
sd
f
s
df
sd
f

farooq
To Top