PHPでクラスのオートロード

naohiro19
記事: 256
登録日時: 15年前
住所: 愛知県

PHPでクラスのオートロード

投稿記事 by naohiro19 » 9年前

PHPでは __autoload を使うことができますが、
現在のhPHPではこの __autoload を使うことが推奨されていません。
ではどうするのかというとspl_autoload_registerを使うことが推奨されています。
new でインスタンスが生成されるたび自動的にファイルを読み込んでくれます。

実装例を見てみましょう。

CODE:

<?php

spl_autoload_register(function($class) {
    $prefix = '\\';
    if(strpos($class, $prefix) === 0) {
        $className = substr($class, strlen($prefix));
        $classFilePath = __DIR__ . '/' . $className . '.php';
        if(file_exists($classFilePath)){
            require $classFilePath;
        }else{
            echo 'No such class :'. $className;
            exit;
        }
    }
});
$prefixは名前空間です。 namespace MyApp; としてしてあるなら $prefix = 'MyApp\\'; としてあげましょう。

CODE:

<?php

class BBS {
}
で $bbs = new BBS() 指定すると BBS.phpが呼ばれて他のPHPファイルからも参照できるようになります
最後に編集したユーザー naohiro19 on 2016年8月19日(金) 09:18 [ 編集 4 回目 ]

コメントはまだありません。