プログラミング言語や環境設定を中心としたパソコン関連の技術メモです。
主にシステム開発中に調べたことをメモしています。TIPS的な位置付けで、気が向いたときにちまちま更新していきます。
PHP、includeとrequireの違い
結論から書けば

include→指定ファイルが読み込めなくても頑張って処理を続ける
require→指定ファイルが読み込めないと力尽きる

の違いです。それだけ。

昔書いたつもりなのですが見つからなかったので、再度(?)書いておきます。

例えば「hoge.php」が無い状態でこんなコードを実行するとφ(--)

<?php

print "■include start<br>\n";

//include
include("hoge.php");

print "□include end<br>\n";
print "■require start<br>\n";

//require
require("hoge.php");

print "□require end<br>\n";

こんな結果になりますφ(--)

■include start

Warning: include(hoge.php): failed to open stream: No such file or directory in C:\xampp\htdocs\test.php on line 6

Warning: include(): Failed opening 'hoge.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\test.php on line 6
□include end
■require start

Warning: require(hoge.php): failed to open stream: No such file or directory in C:\xampp\htdocs\test.php on line 12

Fatal error: require(): Failed opening required 'hoge.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\test.php on line 12

「□require end」までたどり着けませんでした。
requireしようとした時点で力尽きています。

注意点として、これらはあくまで「ファイルが読み込めない場合」です。
読み込んだファイルの中でエラーがある場合は話が変わってきます。

例えば、こんな中身の「hoge.php」を用意してφ(--)

<?php

throw new Exception("throw user exception");

このコードを実行するとφ(--)

<?php

print "■include start<br>\n";

//include
include("hoge.php");

print "□include end<br>\n";
print "■require start<br>\n";

//require
require("hoge.php");

print "□require end<br>\n";

こんな結果になりますφ(--)

■include start

Fatal error: Uncaught exception 'Exception' with message 'throw user exception' in C:\xampp\htdocs\hoge.php:3 Stack trace: #0 C:\xampp\htdocs\test10.php(6): include() #1 {main} thrown in C:\xampp\htdocs\hoge.php on line 3

「□include end」までもたどり着けませんでした。
includeの場合でも処理が途中で止まっちゃいましたね。

まとめると、includeは指定ファイルが読み込めなくても血反吐を吐きながら頑張って処理を続けます。
requireは指定ファイルが読み込めないとそこで諦めてさっさと処理を終了します。
ただしincludeの場合も、読み込んだファイル内でエラーが起これば、その時点で処理は止まります。

個人的には、読み込むべきファイルが読み込めないのに処理を続けるのは違和感があります。
基本的にはrequire使っておいた方が無難っぽい気がしますが、如何でしょう(--?

取りあえず、完了\(--)/
スポンサーリンク
 
このエントリーをはてなブックマークに追加 

category:● PHP  thema:システム開発 - genre:コンピュータ  Posted by ササキマコト 

  関連記事