LoginSignup
4
2

More than 5 years have passed since last update.

PHP7 requireとincludeの違い

Last updated at Posted at 2018-07-04

環境

実行環境は,

WSLのubuntu

OS: VERSION="18.04 LTS (Bionic Beaver)"

PHP: PHP 7.2.5-0ubuntu0.18.04.1 (cli) (built: May 9 2018 17:21:02) ( NTS )

requireとincludeの違い

requireとincludeは, 外部ファイルを読み込む際に使うものです.

いろんなサイトを見ていると, 使い分けの基準が書いてありました.

基準も大事ですが, 今回は, 実際の挙動だけ見ます.

困ったら, 公式ドキュメントphp.netを読もう.

requireの項目を見ると,,,

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

外部ファイルを読み込む時に, エラーの出し方が違うということ.

requireの場合は, スクリプトを止めてしまいます.

includeの場合, warningを出すだけです.

正しく成功したときは, 挙動は全く一緒.

実験してみましょう.

nothing.phpをあえて作らず, 以下の二つのphpスクリプトを実行してみましょう.

test_include.php
<?php
echo "Include nothing.php", PHP_EOL;
include 'nothing.php';
echo "failed to include it", PHP_EOL;
test_require.php
echo "Require nothing.php", PHP_EOL;
require 'nothing.php';
echo "failed to include it", PHP_EOL;

php test_include.phpをたたくと,

Include nothing.php
PHP Warning:  include(nothing.php): failed to open stream: No such file or directory in /var/www/test/test_include.php on line 3
PHP Warning:  include(): Failed opening 'nothing.php' for inclusion (include_path='.:/usr/share/php') in /var/www/test/test_include.php on line 3
failed to include it 

includeに失敗しても, 次の行のecho "failed to include it", PHP_EOL;は実行されています.

次に,

php test_require.phpをたたくと,

Require nothing.php
PHP Warning:  require(nothing.php): failed to open stream: No such file or directory in /var/www/test/test_require.php on line 3
PHP Fatal error:  require(): Failed opening required 'nothing.php' (include_path='.:/usr/share/php') in /var/www/test/test_require.php on line 3 

Fatal error(致命的なエラー)が, 起きて死にましたね.

echo "failed to require it", PHP_EOL;は実行されていません.

ということでした.

perlのように, 外部ファイルを読み込む方法がいくつかあり, それぞれ少し違うといったことはないようです.

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2