基于psr的規(guī)范,使用命名空間和spl_autoload_register()來實(shí)現(xiàn)自動(dòng)加載
文件結(jié)構(gòu):
|--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/>";
}
}
以上這篇PHP 自動(dòng)加載的簡(jiǎn)單實(shí)現(xiàn)(推薦)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考