PHP 自動加載的簡單實現(推薦)


基於psr的規范,使用命名空間和spl_autoload_register()來實現自動加載

 

文件結構:

|--Api

  |--Account.php

  |--User.php

|--Service

  |--Login.php

  |--User.php

|--Application.php

 

Application.php

<?php
use 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

<?php
namespace Api;
 
use Service\Login;
class User{
  public function __construct(){
    echo "User類<br/>";
    new Login();
    new Account();
  }
}

 

Api\Account.php

<?php
namespace Api;
 
class Account{
  public function __construct(){
    echo "Account類<br/>";
  }
}

 

Service\Login.php

<?php
namespace Service;
 
class Login{
  public function __construct(){
    echo "Login類<br/>";
  }
}

 

Service\User.php

<?php
namespace Service;
 
class User{
  public function __construct(){
    echo "Service下的User類<br/>";
  }
}

 

結果:

image.png


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM