目录结构
F:.
│  Power.php
│  Superman.php
│
└─IoC
        Power.php
Superman.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
   | <?php namespace IoC;
 
 
 
 
 
 
 
 
 
 
  spl_autoload_register(function($class){     if($class){         $file = $class.'.php';         if(file_exists($file)){             include_once $file;         }     } });
  class Superman{     protected $power;
      public function __construct()     {                                                                                          $this->power = new Power(999,100);     }
 
 
 
 
 
      public function getPower(){                  return $this->power;     }
 
  }
 
 
  $man = new Superman; echo $man->getPower()->getAbility(); echo "<br>";
  echo Power::class;
   | 
 
Power.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
   | <?php namespace IoC;
 
  class Power{     protected $ability;
      protected $range;
      public function __construct($ability,$range)     {         $this->ability = $ability;         $this->range = $range;     }
      public function getAbility(){         return $this->ability;     } }
   | 
 
自动加载使用的是spl_autoload_register()现在不建议使用__autoload()了
spl_autoload_register('类名')这个函数可以多次加载这比__autoload()只能用一次方便很多利于扩展
而且可以在类中使用就想上面那个例子,而’__autoload()’就不可以了
下面这个例子更好的说明了使用方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
   | <?php
 
 
 
 
 
      define('BASE_PATH',dirname(__FILE__).'/') ;   function cron_autoload1 ($name) {     $file = BASE_PATH.'lib1/'.$name.'.class.php';     if(file_exists($file)){         include_once($file);         return true;     }   } function cron_autoload2 ($name) {     $file = BASE_PATH.'lib2/'.$name.'.class.php';     if(file_exists($file)){         include_once($file);         return true;     } } spl_autoload_register('cron_autoload1'); spl_autoload_register('cron_autoload2');   new Class1(); new Class2();
   | 
 
所以只要有个单独的文件写这些注册的类的地址,然后只要引入这一个文件就好了
以后可以扩展那个文件了
这样就可以实现所有的自动加载.
也就是我最初的疑问,还以为只要use 类 就能自己加载呢 其实是两码事 没那么智能 呵呵
而且命名空间和存放文件地址也未必是一定相对应的,比如最上面第一个例子 Superman的命名空间和地址就不是对应的