DEV Community

Shootacean
Shootacean

Posted on • Edited on • Originally published at shootacean.com

2 2

PHPの include と require の違いについて

PHPで外部モジュールを読み込む際に利用する include, require の違いです。

include と require の使い分けまとめ

指定したモジュールが存在しない場合の挙動が異なります。

  • include の場合、Warning になりスルーされる。
  • require の場合、Fatal error となり処理が終了する。

外部モジュールを読み込んだ後の処理が、外部モジュールに依存しているかどうかによって使い分けましょう。

依存していない場合は include、依存している場合は require です。
基本的にはrequireでいいかと思います。

include と require の実際の挙動を検証してみる

以下のコードを実行して、実際の挙動を確認してみます。

<?php

include('foo');
require('bar');
echo 'Hello';
Enter fullscreen mode Exit fullscreen mode
$ php index.php
Warning: include(foo): failed to open stream: No such file or directory in /Users/shootacean/github.com/shootacean/sandbox/php/include-require/index.php on line 3

Warning: include(): Failed opening 'foo' for inclusion (include_path='.:') in /Users/shootacean/github.com/shootacean/sandbox/php/include-require/index.php on line 3

Warning: require(bar): failed to open stream: No such file or directory in /Users/shootacean/github.com/shootacean/sandbox/php/include-require/index.php on line 5

Fatal error: require(): Failed opening required 'bar' (include_path='.:') in /Users/shootacean/github.com/shootacean/sandbox/php/include-require/index.php on line 5
Enter fullscreen mode Exit fullscreen mode
  • includeでは、Warning となりますが、次の処理へ進むのでrequireが実行されます。
  • requireでは、Fatal error となり処理が終了するので、echo 'Hello';は実行されません。

ビジネスロジックのコアな部分の外部モジュールを利用する際などには、

requireを利用することでモジュール読み込み時点で致命的なエラーに気づくことができます。

ビュー層などの致命的な問題にならない箇所では include でいいかと思います。

以上、PHPの includerequire の挙動の違いについてでした。

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay