2010-11-17 70 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'); 

这将调用静态初始化从上面()函数后进行。