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

猜你喜欢

转载自blog.csdn.net/qq_33253054/article/details/107992683