php的自动加载

 

php的自动加载:php

在php5之前,咱们要用某个类或类的方法,那必须include或者require,以后才能使用,每次用一个类,都须要写一条include,麻烦html

php做者想简单点,最好能引用一个类时,若是当前没有include进来,系统能自动去找到该类,自动引进~函数

因而:__autoload()函数应运而生。ui

一般放在应用程序入口类里面,好比discuz中,放在class_core.php中。spa

先讲浅显的例子:htm

第一种状况:文件A.php中内容以下blog

<?phpio

class A{function

  public function __construct(){class

         echo 'fff';

  }

}

?>

文件C.php 中内容以下:

<?php   
function __autoload($class)   
{   
$file = $class . '.php';   
if (is_file($file)) {   
require_once($file);   
}   
}   

$a = new A(); //这边会自动调用__autoload,引入A.php文件

?>

第二种状况:有时我但愿能自定义autoload,而且但愿起一个更酷的名字loader,则C.php改成以下:

<?php
function loader($class)
{
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}

spl_autoload_register('loader'); //注册一个自动加载方法,覆盖原有的__autoload

$a = new A();

?>

第三种状况我但愿高大上一点,用一个类来管理自动加载

<?php   
class Loader   
{   
public static function loadClass($class)   
{   
$file = $class . '.php';   
if (is_file($file)) {   
require_once($file);   
}   
}   
}   

spl_autoload_register(array('Loader', 'loadClass'));   

$a = new A();

?>

当前为最佳形式。

一般咱们将spl_autoload_register(*)放在入口脚本,即一开始就引用进来。好比下面discuz的作法。

if(function_exist('spl_autoload_register')){

  spl_autoload_register(array('core','autoload'));  //若是是php5以上,存在注册函数,则注册本身写的core类中的autoload为自动加载函数

}else{

  function __autoload($class){         //若是不是,则重写php原生函数__autoload函数,让其调用本身的core中函数。

    return core::autoload($class);

  }

}

这段扔在入口文件最前面,天然是极好的~

 

相关连接:

http://www.cnblogs.com/myluke/archive/2011/06/25/2090119.html  //good

http://www.php100.com/html/php/lei/2013/0905/5267.html

相关文章
相关标签/搜索