440   PHP

一,背景

1,PHP实例化对象时,如果类文件不在同一文件,则需要include进来,否则会报找不类的错

C:\Users\luckybird\Desktop\test>php autoload.php

Fatal error: Class 'test' not found in C:\Users\luckybird\Desktop\test\autoload.php on line 11

2,如果多个文件时,那么需要一个个include进来会变得非常麻烦,于是PHP提供autoload()的方法,来自动加载需要实例化的类

3,后来PHP还提供了spl_autoload_register()函数,可以添加多个加载函数而不只是一个autoload(),或者调用新的autoload()而不是原来的autoload,spl_autoload_register显得更加灵活。

 

二,autoload的示例代码
在同一个目录下
1,test.php文件内容

class test{
	
	//实例化对象时被调用
	public function __construct() {
		echo 'initializing test',"\n";
	}
	
}

 

2,autoload.php文件内容

// 自动加载需要实例化的类
function __autoload($classname) {
	echo 'autoload classname:'.$classname,"\n";
    $filename = './'.$classname.'.php';
    include_once($filename);
}

$obj = new test();

3,测试结果

C:\Users\luckybird\Desktop\test>php autoload.php
autoload classname:test
initializing test

 

三,spl_autoload_register示例代码

1,在one目录新建test_one.php文件,内容

class test_one{
	
	public function __construct() {
		echo 'initializing test_one',"\n";
	}
	
}

2,在two目录新建test_two.php文件,内容

class test_two{
	
	public function __construct() {
		echo 'initializing test_two',"\n";
	}
	
}

3,在one,two的当前目录下新建autoload.php文件,内容

// 多个自动加载器
function one_loader($classname) {
	echo 'one_loader autoload classname:'.$classname,"\n";
	$file = './one/'.$classname.'.php';
	if(file_exists($file)){
		include_once($file);
	}else{
		echo $classname.' is not in one floder',"\n";
	}
    
}

function two_loader($classname) {
	echo 'two_loader autoload classname:'.$classname,"\n";
	$file = './two/'.$classname.'.php';
	if(file_exists($file)){
		include_once($file);
	}else{
		echo $classname.' is not in two floder',"\n";
	}
}

// 注册到自动加载
spl_autoload_register('one_loader');
spl_autoload_register('two_loader');

echo "\n";
$test_one = new test_one();
echo "\n";
$test_two = new test_two();

4,测试结果

C:\Users\luckybird\Desktop\test>php autoload.php

one_loader autoload classname:test_one
initializing test_one

one_loader autoload classname:test_two
test_two is not in one floder
two_loader autoload classname:test_two
initializing test_two


从结果可看出,spl_autoload_register会按设定的顺序调用已经注册的自动加载器,尝试加载需要实例化的类




Leave a Reply

Your email address will not be published. Required fields are marked *