This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

外部ファイルから処理を読み込み(関数、名前空間、クラス)

Last updated at Posted at 2024-02-12

外部ファイルから処理を読み込む

関数の読み込み

  • index.phpに関数を設定
  • require.phpで関数を実行

index.php

<?php
function txt_echo(){
  echo 'テストテキスト!';
}
?>

require.php

※index.phpを読み込み、関数を実行

<?php
require_once 'index.php';
txt_echo();
?>

実行結果(require.php)

テストテキストです

ファイル分割を使った時によく用いられる記述

※「txt_echo」関数の記述が無い場合のみ「txt_echo」関数を宣言する
※function_exists — 指定した関数が定義されている場合に true を返す

index.php

<?php
if(!function_exists('txt_echo')){
    function txt_echo(){
        echo 'テストテキスト!';
      }
}
?>

クラスの読み込み

  • index.phpにクラスを設定
  • require.phpでクラスを生成、処理を実行

index.php

※クラスの設定。変数とコンストラクタ、関数を設定

<?php

class TestClass{
  protected $test_txt;
  function __construct(){
    $this->test_txt = 'テストテキストです';
  }

  function txt_echo(){
    echo $this->test_txt;
  }
}
?>

require.php

※index.phpを読み込み、クラスを生成。クラス内に設定された関数を実行

<?php
require_once 'index.php';

$test_class = new TestClass();
$test_class->txt_echo();
?>

実行結果(require.php)

テストテキストです
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