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/>";
  }
}
결과:
 
이상 의 PHP 가 자동 으로 불 러 오 는 간단 한 실현(추천)은 바로 편집장 이 여러분 에 게 공유 하 는 모든 내용 입 니 다.여러분 에 게 참고 가 되 고 저희 도 많이 응원 해 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기