php自動載方法有兩種.

來源:互聯網
上載者:User

標籤:reflect   ade   getc   dex   on()   bsp   contain   row   container   

但有一問題沒有解決, 就是在include前判斷檔案是否存在的問題.

12345678910111213 set_include_path(‘aa‘ . PATH_SEPARATOR . get_include_path());function __autoload($className){    //如果加這個檢測, 因為此檔案不在目前的目錄下,它就會檢測不到檔案存在,    //但include是能成功的    if (file_exists($className . ‘.php‘)) {   include_once($className . ‘.php‘);    } else {        exit(‘no file‘);    }} $a = new Acls();

第二種方案用spl自動載入,這裡具體說一下這個.

spl_autoload_register()

一個簡單的例子

12345678910111213 set_include_path(‘aa‘ . PATH_SEPARATOR . get_include_path());//function __autoload($className)//{//    if (file_exists($className . ‘.php‘)) {//        include_once($className . ‘.php‘);//    } else {//        exit(‘no file‘);//    }//} spl_autoload_register(); $a = new Acls();

spl_autoload_register()會自動先調用spl_autoload()在路徑中尋找具有小寫檔案名稱的".php"程式.預設尋找的副檔名還有".ini",還可以用spl_autoload_extenstions()註冊副檔名.

在找不到的清況下,還可以通過自己定義函數尋找

function loader1($class)

{

//自己寫一些載入的代碼

}

function loader2($class)

{

//當loader1()找不到時,我來找

}

spl_autoload_register(‘loader1‘);

spl_autoload_register(‘loader2‘);

還可以更多........

MVC架構是如何?自動載入的

首先設定路徑

    ‘include‘ => array(        ‘application/catalog/controllers‘,        ‘application/catalog/models‘,        ),

$include = array(‘application/controllers‘, ‘application/models‘, ‘application/library‘);

set_include_path(get_include_path() . PATH_SEPARATOR .implode(PATH_SEPARATOR, $config[‘include‘]));

在擷取URL,解析出控制器與方法.

然後設定自動載入

123456789101112131415161718 class Loader{    /**     * 自動載入類     * @param $class 類名     */    public static function autoload($class)    {        $path = ‘‘;            $path = str_replace(‘_‘, ‘/‘, $class) . ‘.php‘;        include_once($path);    }} /** * sql自動載入 */spl_autoload_register(array(‘Loader‘, ‘autoload‘));
路由,執行個體化控制器,調用方法,你寫的東西就開始執行了
12345678910111213141516 /** * 路由 */public function route(){    if (class_exists($this->getController())) {        $rc = new ReflectionClass($this->getController());        if ($rc->hasMethod($this->getAction())) {            $controller = $rc->newInstance();            $method = $rc->getMethod($this->getAction());            $method->invoke($controller);        } else            throw new Exception(‘no action‘);    } else        throw new Exception(‘no controller‘);}
1  
1 初步的自動載入就完成了

php自動載方法有兩種.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.