入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

php加载外部文件类的3.5个方法

创建时间:2015-06-26 投稿人: 浏览次数:2272
<?php
/*
	 第一种方法 require:缺点就是如果加载文件过多,需要多个require
 */
// require("A.CLASS.PHP");
// require("B.CLASS.PHP");

/*
	 第二种方法__autoload 
	 PHP5在new 一个没有存在的类,会自动调用这个__autoload函数,____autoload只是去include_path寻找类文件并加载
     php中类名和函数名不区分大小写。。
 */
function __autoload($class)
{

	if(is_file($class.".CLASS.PHP")){
	// require($class.".CLASS.PHP");
	// 
	}
}
/*
	 第三种方法:自定义autoload,调用spl_autoload_register函数
	
 */
function myload($class){// myload 让我想起来权利的游戏中的一句台词:yes my lord
	if(is_file($class.".CLASS.PHP"))
	require($class.".CLASS.PHP");
}

// spl_autoload_register("myload");


/*
	 第三点五种方法:自定义autoload,调用spl_autoload_register函数
	 但是可以调用类的某个方法,数组方式调用,但是必须是静态方法,否则会报错 
	
 */
class Lorder{

	public  function load($class){

		if(is_file($class.".CLASS.PHP")){
			require($class.".CLASS.PHP");
		}

	}
}

spl_autoload_register(array("Lorder","load"));


$b =new A();//1
$B=new B();//2
$c=new a();// still 1
$d=new bq();// 3

ps

如果试图加载多个文件后缀名的文件比如想要实现类似下面的效果:

function __autoload($classname){
        if(is_file($classname.".php"){
            include $classname.".php";
        } elseif(is_file($classname.".inc"){
            include $classname.".inc";
        }
    }
那么用上面的spl_autoload_register()怎样更好的实现呢

答案是:

后面加上这句:

sql__autoload_extensions(".php,.inc");//用逗号隔开就行

spl_autoload_extensions(".php,.inc,.some");


以上内容来自于opencart2.0源码:


spl_autoload_register("autoload");
spl_autoload_extensions(".php");

//也可以将下面的require 替换为下面7行
//function myload($class){
//    $file=DIR_SYSTEM."engine/".$class.".php";
//    if(file_exists($file)){
//     require_once(modification($file));   
//    }
//}
//spl_autoload_register("myload");
// Engine
require_once(modification(DIR_SYSTEM . "engine/action.php"));
require_once(modification(DIR_SYSTEM . "engine/controller.php"));
require_once(modification(DIR_SYSTEM . "engine/event.php"));
require_once(modification(DIR_SYSTEM . "engine/front.php"));
require_once(modification(DIR_SYSTEM . "engine/loader.php"));
require_once(modification(DIR_SYSTEM . "engine/model.php"));
require_once(modification(DIR_SYSTEM . "engine/registry.php"));


声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。