PHPで外部ファイルを読み込む

PHPで外部ファイルを読み込む方法を試してみます。

サンプルコード

まずは読み込む外部ファイルを用意します。

External.php

<?php
$str = 'テスト';

外部ファイルを読み込む場合、requireやincludeが使えます。
requireで外部ファイルを読み込んでみます。

PHP

<?php
require "External.php";
echo $str;
?>

requireのデモページ

次にincludeで外部ファイルを読み込んでみます。

PHP

<?php
include "External.php";
echo $str;
?>

includeのデモページ

ファイルが見つからなかった場合

読み込むファイルが見つからなかったときの挙動が少し違います。

PHP

<?php
require "Hoge.php";
echo $str;
?>

requireの場合はFatal errorが表示されて、そこで処理が止まります。

Warning: require(Hoge.php): failed to open stream: No such file or directory in /xxx/sample/reads-an-external-file-with-php/index3.php on line 16
Fatal error: require(): Failed opening required 'Hoge.php' in /xxx/sample/reads-an-external-file-with-php/index3.php on line 16

 

PHP

<?php
include "Hoge.php";
echo $str;
?>

includeの場合はWarningが表示されますが、処理は続行されます。

Warning: include(Hoge.php): failed to open stream: No such file or directory in /xxx/sample/reads-an-external-file-with-php/index4.php on line 16
Warning: include(): Failed opening 'Hoge.php' for inclusion in /xxx/sample/reads-an-external-file-with-php/index4.php on line 16

他にもrequire_onceやinclude_onceなどがありますが、今回は省略します。
 

【参考サイト】

 

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年3月
 12
3456789
10111213141516
17181920212223
24252627282930
31