這篇文章主要介紹了關於PHP 自動載入的簡單實現,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下
基於psr的規範,使用命名空間和spl_autoload_register()來實現自動載入
檔案結構:
|--Api
|--Account.php
|--User.php
|--Service
|--Login.php
|--User.php
|--Application.php
Application.php
<?phpuse Api\User;use Service\User as User2;class Application{ public static function main(){ self::registe(); new User(); new User2(); } public static function registe(){ spl_autoload_register("Application::loadClass"); } public static function loadClass($class){ $class=str_replace('\\', '/', $class); $class="./".$class.".php"; require_once $class; }}Application::main();
Api\User.php
<?phpnamespace Api;use Service\Login;class User{ public function __construct(){ echo "User類<br/>"; new Login(); new Account(); }}
Api\Account.php
<?phpnamespace Api;class Account{ public function __construct(){ echo "Account類<br/>"; }}
Service\Login.php
<?phpnamespace Service;class Login{ public function __construct(){ echo "Login類<br/>"; }}
Service\User.php
<?phpnamespace Service;class User{ public function __construct(){ echo "Service下的User類<br/>"; }}
結果: