クラスのオートローディング(サンプル3)

概要

クラスを外部ファイルに定義している場合はrequireまたはincludeで処理してから使用する必要があるが、__autoloadを使用することで簡略化する


サンプル3

定義

$WORK_DIR/
|__ main.php
|  |__ classes/
|     |__ Test1.class.php
|     |__ Test2.class.php
 
 

対象ファイル

main.php
<?php
 
// autoloadのクラスを配置するパス
define('CLASS_PATH', 'classes/');
 
// autoload例外用の例外
class AutoloadException extends Exception { }
 
// 自動ロードを行うクラス
class AutoloadClass {
 
	public static function autoload($sClassName) {
 
		// reuiqreでは存在しないことで終了してしまうので継続させるためにincludeを使用
        @include_once(CLASS_PATH . $sClassName . '.class.php');
 
        // クラスチェック
        if (class_exists($sClassName)) {
            // クラスが存在する場合はここで抜ける
            return;
        }
 
        // クラスが存在しない場合は例外発行用のクラスを動的に用意
        eval("class $sClassName {
            function __construct() {
                throw new AutoloadException('Class $sClassName not found');
            }
 
            static function __callstatic(\$m, \$args) {
                throw new AutoloadException('Class $sClassName not found');
            }
        }");
    }
}
 
// __autoload() の実装として登録する
spl_autoload_register(array('AutoloadClass', 'autoload'));
 
try{
	// クラスのインスタンスを生成
	$a = new Test1();
	$a->method1();
 
	// クラスの静的メソッドを実行
	Test2::method1();
 
	// クラスの静的メソッドを実行
	$b = new Test3();
 
}catch(AutoloadException $e){
	// 例外メッセージを表示
	echo $e->getMessage() . "\n";
 
}
 
 
classes/Test1.class.php
<?php
// テスト用クラス
<?php
// テスト用クラス
class Test1{
 
	// コンストラクタ
	function __construct(){
		echo __CLASS__ . "::" . "__construct" . "\n";
	}
 
	// デストラクタ
	function __destruct(){
		echo __CLASS__ . "::" . "__destruct" . "\n";
	}
 
	// 動的メソッド
	public static function method1(){
		echo __CLASS__ . "::" . "method1" . "\n";
	}
}
 
 
classes/Test2.class.php
<?php
// テスト用クラス
class Test2{
 
	// コンストラクタ
	function __construct(){
		echo __CLASS__ . "::" . "__construct" . "\n";
	}
 
	// デストラクタ
	function __destruct(){
		echo __CLASS__ . "::" . "__destruct" . "\n";
	}
 
	// 静的メソッド
	public static function method1(){
		echo __CLASS__ . "::" . "method1" . "\n";
	}
}
 
 

結果




最終更新:2012年07月07日 11:49