9cubed
ブログ | Tailwind | Vite | Python | Node.js | Linux | PowerShell | その他 | 将棋ウォーズ | 歌の練習
< 前の記事

PHP - ファイル入出力

次の記事 >

PHP - namespace(名前空間)

PHP

PHP - 他のPHPファイルの読み込み

公開日:2020-12-22
更新日:2020-12-22

1. 概要

実行中のPHPファイルに、他のPHPファイルを挿入するには、include または require を使います。
include と require の違いは、ファイルが読み込めなかった場合の動作です。
include は、ファイルが読み込めなくても処理を続行しますが、
require は、ファイルの読み込みに失敗した時点でエラーとなり、処理が終了します。
正常に読み込んだファイルの中でエラーが発生した場合は、どちらも処理が終了します。

また、後ろに _once を付けると、何度実行しても、1度だけ挿入されます。
ライブラリなどを読み込む際には、require_once() を使うと良いと思います。
include      'パス';
include_once 'パス';
require      'パス';
require_once 'パス';

2. 使用例

test.php に、test2.php を3回挿入しています。

test.php
<?php
    print("test\n");
    include 'test2.php';
    include 'test2.php';
    include 'test2.php';
    print("test\n");
test2.php
<?php
    print("test2\n");
実行結果
test
test2
test2
test2
test

include() を include_once() にすると、test2.php は1度だけ読み込まれるため、次のような実行結果となります。
実行結果
test
test2
test

< 前の記事

PHP - ファイル入出力

次の記事 >

PHP - namespace(名前空間)

YouTube X

新着一覧

  • SCSS のインストールVite
  • Tailwind CSS のプロジェクトの作成Tailwind
  • TypeScriptのプロジェクトの作成Vite
  • Flask のインストールと動作確認Python
  • 簡易Webサーバーの作成Python
  • pipeline で文章の生成Python
  • pipeline で文章の要約Python
  • 音声から文字起こしPython
  • Node.js のインストールNode.js
  • .ps1(PowerShellスクリプト)を実行可能にするPowerShell

アーカイブ

  • 2025/12
  • 2025/11
  • 2025/10
  • 2025/09
  • 2025/08

以前のカテゴリー一覧

  • CakePHP3
  • CentOS7
  • HTML・CSS・JavaScript
  • Haskell
  • JavaScript
  • Kotlin
  • Laravel5
  • PHP
  • Python
  • Ruby
  • RubyOnRails5
  • TypeScript
  • Vue.js
  • Webサーバ講座
  • Webプログラミング講座
  • jQuery
  • linux
  • パソコン講座
  • ブログ
  • プログラミング講座
  • メモ帳作成講座
  • 数学

Copyright © 9cubed. All Rights Reserved.

プライバシーポリシー 利用規約
▲