php自动加载类

  1. 自动加载类:AutoLoadController.php

     <?php
    
     class AutoLoadController
     {
         private $base_dir;
    
         public function __construct() {
             $this->base_dir = __DIR__;
             spl_autoload_register(array($this,'autoLoad'));
         }
    
         public function autoLoad($classname){
             $file_path = $this->base_dir . DIRECTORY_SEPARATOR . $classname .".php";
             if(file_exists($file_path)){
                 include_once($file_path);
             }
         }
     }
    
  2. 调用自动加载类:index.php

     <?php
    
     require_once ('AutoLoadController.php');
    
     new AutoLoadController();
    
     $opt = getopt("c::a::",array());
     $controller = $opt['c']?$opt['c']:'defaultClass';
     $action     = $opt['a']?$opt['a']:'defaultAction';
     $obj = new $controller();
     $obj->$action();
    
  3. 类文件1:Class1.php
     <?php
     class Class1{
         public function action1(){
             echo "I'm Class1->action1";
         }
         public function action2(){
             echo "I'm Class1->action2";
         }
         public function defaultAction(){
             echo "I'm Class1->defaultAction";
         }
     }
    
  4. 类文件2:Class2.php

     <?php
    
     class Class2{
         public function action1(){
             echo "I'm Class2->action1";
         }
         public function action2(){
             echo "I'm Class2->action2";
         }
         public function defaultAction(){
             echo "I'm Class2->defaultAction";
         }
     }
    
  5. 类文件3:defaultClass.php

     <?php
    
     class defaultClass{
         public function action1(){
             echo "I'm defaultClass->action1";
         }
         public function action2(){
             echo "I'm defaultClass->action2";
         }
         public function defaultAction(){
             echo "I'm defaultClass->defaultAction";
         }
     }
    
@耿志环 2012-∞ 冀ICP备17033181号, powered by Gitbook修订: 2018-05-23 16:25:59

results matching ""

    No results matching ""