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

<?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'));


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值