php自动载方法有两种.

但有一问题没有解决, 就是在include前判断文件是否存在的问题.php

1
2
3
4
5
6
7
8
9
10
11
12
13
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自动加载,这里具体说一下这个.sql

spl_autoload_register()app

一个简单的例子框架

1
2
3
4
5
6
7
8
9
10
11
12
13
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()注册扩展名.函数

在找不到的清况下,还能够经过本身定义函数查找this

spa

function loader1($class)code

{ci

//本身写一些加载的代码路由

}

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,解析出控制器与方法.

而后设置自动加载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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' ));
路由,实例化控制器,调用方法,你写的东西就开始执行了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
  * 路由
  */
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
初步的自动加载就完成了
相关文章
相关标签/搜索