2010-11-17 72 views
0

我對PHP5/OOP很陌生,無法真正理解下面的代碼是如何工作的。在研究__autoload()函數時,在PHP.net文檔中找到它。PHP OOP:這段代碼是如何工作的?

我該怎麼稱呼它? new MyClass1();autoloader::model('myModel');

The snippet:

class autoloader { 

    public static $loader; 

    public static function init() 
    { 
     if (self::$loader == NULL) 
     self::$loader = new self(); 

     return self::$loader; 
    } 

    public function __construct() 
    { 
     spl_autoload_register(array($this,'model')); 
     spl_autoload_register(array($this,'helper')); 
     spl_autoload_register(array($this,'controller')); 
     spl_autoload_register(array($this,'library')); 
    } 

    public function library($class) 
    { 
     set_include_path(get_include_path().PATH_SEPARATOR.'/lib/'); 
     spl_autoload_extensions('.library.php'); 
     spl_autoload($class); 
    } 

    public function controller($class) 
    { 
     $class = preg_replace('/_controller$/ui','',$class); 

     set_include_path(get_include_path().PATH_SEPARATOR.'/controller/'); 
     spl_autoload_extensions('.controller.php'); 
     spl_autoload($class); 
    } 

    public function model($class) 
    { 
     $class = preg_replace('/_model$/ui','',$class); 

     set_include_path(dirname(__FILE__) . PATH_SEPARATOR.'/model/'); 
     spl_autoload_extensions('.model.php'); 
     spl_autoload($class); 
    } 

    public function helper($class) 
    { 
     $class = preg_replace('/_helper$/ui','',$class); 

     set_include_path(get_include_path().PATH_SEPARATOR.'/helper/'); 
     spl_autoload_extensions('.helper.php'); 
     spl_autoload($class); 
    } 

} 

回答

1
$autoloader = autoloader::init(); 

這會給你自動加載機實例。這個班希望成爲一個單身人士。

所有的__autoloader都是php最後一分鐘嘗試找到一個尚未包含的類。如果你有一個好的命名/目錄結構,你不需要擔心包含/需要你自己的任何類...自動加載器會爲你做。

,如果你想打電話模型功能:

$autoloader->model('Model'); 

這將調用靜態初始化從上面()函數後進行。