php自动加载

php中有两种自动加载机制函数

__autoload();

spl_autoload_register();

1. __autoload()

可以将需要使用类的时候把文件加载到程序中

<?php

function __autoload($className) {

    if (file_exists($className . '.php')) {

        include $className . '.php';//可细化

    } else {

        echo $className . '.php is not exists.';

        exit;

    }

}



$indexController = new IndexController();

在程序的运行过程中,php会检测这个$className类是否已经加载,如果没有加载会去执行__autoload(),再去加载$className这个类。在实例化类的对象、访问类中的静态变量和方法等都会去检测类是否已经加载,是否有定义__autoload()函数,如果都没有就会报错。

在复杂点的系统中,用__autoload()来实现类的自动加载可能会很复杂。

2. spl_autoload_register()

<?php
spl_autoload_register();
$index = new Index();

spl_autoload_register()函数中没有参数,则会自动默认实现void spl_autoload ( string $class_name [,string $file_extensions ] )函数,默认支持.php和.ini

function load1($className) {
    //include
}
function load2($className) {
    //include
}

spl_autoload_register('load1');//注册到spl_autoload_functions
spl_autoload_register('load2');

$index = new Index();

会先通过load1去加载类,如果load1中没有,再通过load2去加载,如果还有以次类推。

实现一个自动加载方法比较多,这举例一个

转自http://cn2.php.net/autoload ,Thank tofka at fatihkadirakin dot com

<?php
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(get_include_path().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);
    }

}

//call
autoloader::init();
?>

也可以根据自己的需要来设计实现

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值