2011-12-12 26 views

回答

2

沒有真正的任何重大差異。

的封蓋(像下面(PHP定義5.3+只))不能被註銷,除非它被保存到一個變量:

spl_autoload_register(function($class) { ... }); 

靜態方法實際上可以自動運行前加載靜態類其自動裝載機

spl_autoload_register(function($class) { 
    if ($class === 'AutoLoader') { 
     var_dump('Auto loading AutoLoader'); 
     class AutoLoader { 
      public static function autoload($class) { 
       var_dump(__CLASS__ . ' is loading: ' . $class); 
      } 
     } 
    } 
}); 

spl_autoload_register('AutoLoader::autoload'); 

Test::func(); 

// 'Auto loading AutoLoader' 
// 'AutoLoader is loading: Test' 

雖然,我不知道你爲什麼想要這樣做。

雖然靜態調用更容易取消註冊。

無論哪種方式,你應該遵循PSR0自動裝載標準:https://gist.github.com/221634

0

如果使用非靜態調用,也解決文件路徑和類的名稱空間動態的優勢。

class SimpleFactory { 
protected $path, $namespace; 

    function __construct($path, $namespace) { 
     $this->path = $path; 
     $this->namespace = $namespace; 
     spl_autoload_register(array($this, 'autoload')); 
    } 

    function __destruct() { 
     spl_autoload_unregister(array($this, 'autoload')); 
    } 

    function produce($name) { 
     if (class_exists($name, $autoload = true)) { 
      return new $name(); 
     } else throw new RuntimeException("Unable to produce {$name}"); 
    } 

    public function autoload($name) { 
     $class_name = str_replace($this->namespace, '', $name); 
     $filename = $this->path.$class_name.'.php'; 
     if (file_exists($filename)) 
      require $filename; 
    } 

} 

嘗試

$a = new SimpleFactory('path1/', 'anames\\'); 
$a1 = SimpleFactory->produce('a'); 

get_class($ A1)== anames \一

$b = new SimpleFactory('path2/', 'bnames\\'); 
$b1 = SimpleFactory->produce('a'); 

get_class($ B1)== bnames \一

對於更廣泛的例子,請參閱我的回答Throwing Exceptions in an SPL autoloader?