php初学(六) --------------- 自制mvc框架(自动加载类)

这里主要讲述自动加载类。

spl_autoload_register是php内置的函数,当 new class时如果没有,会自动执行spl_autoload_register函数。

Autoload.php

<?php
//自动加载类
//加载application文件夹里的类
//需要文件名与控制器名一样
	spl_autoload_register(function ($classname) {
		$name  = $classname;
	    $filePath_one = APP_PATH.$name.'.php';
	    if (file_exists($filePath_one)) {
	    	include_once $filePath_one;
	    }else{
	    	$filePath_one = APP_PATH.'class/'.$name.'.class.php';
	    	if (file_exists($filePath_one)) {
		    	include_once $filePath_one;
		    }else{
		    	echo "404";
		    }
	    }

	});
?>
<?php
	//第一种方式
function __autoload($classname) {
    if ($classname === 'xxx.php'){
        $filename = "./". $classname .".php";
        include_once($filename);
    } else if ($classname === 'yyy.php'){
        $filename = "./other_library/". $classname .".php";
        include_once($filename);
    } else if ($classname === 'zzz.php'){
        $filename = "./my_library/". $classname .".php";
        include_once($filename);
    }
    // blah
}
//第二种方式
spl_autoload_register(function($className){
    
    $filePath = __DIR__.DIRECTORY_SEPARATOR."...".DIRECTORY_SEPARATOR;
    //完整类名
    $completeClassName = $filePath.$className;
    if(class_exist($filePath.$className)){ //或者file_exist()
        include_once($completeClassName.".php");
    }else{
        throw new Exception("can't find this class(".$class.")!");
    }
})
	//第三种方式
	spl_autoload_register('my_library_loader');
	spl_autoload_register('other_library_loader');
	spl_autoload_register('basic_loader');

	function my_library_loader($classname) {
	    $filename = "./my_library/". $classname .".php";
	    include_once($filename);
	}
	function other_library_loader($classname) {
	    $filename = "./other_library/". $classname .".php";
	    include_once($filename);
	}
	function basic_loader($classname) {
	    $filename = "./". $classname .".php";
	    include_once($filename);
	}
?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值