版本


PHP5.1.2 之前使用 __autoload() 。

PHP5.1.2 之后使用 spl_autoload_register() 。

本文以 spl_autoload_register() 进行演示 。


包含目录


application/controllers

application/models

application/libs


代码实现


//包含目录

$include_dir = [

  'application/controllers',

  'application/models',

  'application/libs'

]

//设置包含目录

set_include_path(get_include_path() . PATH_SEPARATOR .implode(PATH_SEPARATOR, $include_dir));

/**

 * 自动加载类库

 * @param string $class 类名

 */

function auto_load_class($class = '')

{

    //在这可以进行扩展,默认是将类名转成小写。

    //可扩展方向:文件夹_类名 

    $path = strtolower($class) . '.class.php';

    include_once($path);

}

spl_autoload_register('auto_load_class'); //spl注册自动加载

$obj = new 类名(); //实例化

$obj->方法名();

当指定了多个目录且有相同名称的文件时,以排位居前目录下的为准。




Thanks ~