LoginSignup
0
0

More than 5 years have passed since last update.

PHP Manual 読書会(8回目)(制御構造2)

Posted at

PHPに慣れる為に週1ぐらいで更新していきます。PHP Manualを読んで実験して行きます。

前回:PHP Manual 読書会(7回目)(制御構造1)

include

include 文は指定されたファイルを読み込み、評価します。

  • 直接pathを指定しない場合はinclude_pathに書かれたpathからファイルを探します。
    • include_pathが影響を及ぼす関数
    • require
    • include
    • fopen()
    • file()
    • readfile()
    • filet_get_content()
    • set_include_path() を使用すると実行時に変更することができる

重要なポイントとして、ファイルが見つけられない場合はwariningsを発行する。

include は、ファイルを見つけられない場合に warning を発行

<?php

include('./hoge.php'); // 存在しないファイルを読み込む
PHP Warning:  include(./hoge.php): failed to open stream: No such file or directory

set_include_pathを使用する

tree dir
dir
└── hoge.php

このようなディレクトリにhoge.phpを置く。

// hoge.php
<?php

function say() {
    echo "hello\n";
}

set_include_pathを使用して読み込む。

<?php

set_include_path('./dir');

include('hoge.php');

say();

読み込まれたファイルの扱い

ファイルが読み込まれるとそのファイルに含まれるコードは、 includeもしくはrequireが実行された 行の変数スコープを継承します。 呼び出し側の行で利用可能である全ての変数は、読み込まれたファイル内で利用可能です。 しかし、読み込まれたファイル内で定義されている関数やクラスはすべて グローバルスコープとなります。

つまり、どこか実行時の関数内とかで呼び出した場合はそのスコープへアクセスできるのか。出来なかった。なかで関数返した場合に可能とかそういう感じかなこれ。

require

require は include とほぼ同じですが、失敗した場合に E_COMPILE_ERROR レベルの致命的なエラーも発生するという点が異なります。

<?php

require('./hoge.php');
PHP Warning:  require(./hoge.php): failed to open stream: No such file or directory

PHP Fatal error:  require(): Failed opening required './hoge.php'

warningsと一緒に致命的なエラーも出た。requireの方は出来なかったら止まったほうがいいけーすで使えそうだ。内部的に同じロジックを使用しているのか、warningsまで出ている。あとでコードを確認したい。

require_once

include_once は、スクリプトの実行時に同じファイ ルが複数回読み込まれ、評価される可能性がある場合に、関数の再定義や 変数値の再代入といった問題を回避するために一回だけ読み込ませるため に使用します。

例えば、cakephpだと以下の様に使われていたりする。

public function bootstrap()
{
    require_once $this->configDir . '/bootstrap.php';
}

1回しか読み込みたくないconfig系で使われているようだ。

0
0
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
0
0