php自动加载函数
思考:
- 为什么需要自动加载?
- 自动加载函数有哪些?
- 对于自动加载函数的区别和选择理由
为什么需要自动加载
现在我么来建一个小项目
- 目录结构:
| AotuLoad
| - Controller
| - - TestController.php
| - Model
| - - TestModel.php
| - index.php
- TestController.php
namespace AotoLoad\Controller;
use AotoLoad\Model\TestModel;
class TestController {
public function test(){
$model = new TestModel();
echo $model->test();
}
}
- TestModel.php
namespace AotoLoad\Model;
class TestModel{
public function test(){
return 'TestModel->test()';
}
}
- index.php
require_once __DIR__.'\Controller\TestController.php';
require_once __DIR__.'\Model\TestModel.php';
$controller = new AotoLoad\Controller\TestController();
$controller->test();//这是能正常运行的
我们想要在index.php中使用TestController.php 就必须引入使用到的所有文件,否则就会报错。所以在大型项目中,不使用自动加载就会出现无数个require_once,所以这时候自动加载就出现了。
自动加载函数 __autoload($class)
/**
* php程序在发现使用的类没有被包含的话 会执行这个方法
* @param $class 包含namesoace+类名
*/
function __autoload ($class){
}
修改index.php:
//require_once __DIR__.'\Controller\TestController.php';
//require_once __DIR__.'\Model\TestModel.php';
function __autoload($class){
$classPath = dirname(__DIR__).'\\'.$class.'.php';
if(file_exists($classPath)){
require_once ($classPath);
}else{
echo $classPath."不存在";
}
}
$controller = new AotoLoad\Controller\TestController();
$controller->test();
没有报错,输出:
TestModel->test()
自动加载函数 spl_autoload_register
(PHP >= 5.1.2)
/**
* @param $autoload_function 回调函数
* @param $throw 此参数指定当无法注册autoload_函数时,spl_autoload_register()是否应引发异常。默认为true
* @param $prepend 如果是 true,spl_autoload_register() 会添加函数到队列之首,而不是队列尾部。
*/
function spl_autoload_register ($autoload_function = null, $throw = true, $prepend = false) {}
修改index.php:
//require_once __DIR__.'\Controller\TestController.php';
//require_once __DIR__.'\Model\TestModel.php';
function test_autoload($class){
$classPath = dirname(__DIR__).'\\'.$class.'.php';
if(file_exists($classPath)){
require_once ($classPath);
}else{
echo $classPath."不存在";
}
}
spl_autoload_register('test_autoload');
$controller = new AotoLoad\Controller\TestController();
$controller->test();
为什么__autoload()函数最后还是被废弃了呢?
- 因为随着php的发展,项目越来越大,当一个php项目大到一定程度时可能会遇到需要调用不同项目的文件,因为__autoload函数不能被多次调用,所以就不适用了,
- php5.3之前 __autoload函数的错误不能被catch函数捕获,会抛出致命错误,5.3之后才能够 thrown 自定义的异常(Exception),随后自定义异常类即可使用。 __autoload 函数可以递归的自动加载自定义异常类。
优胜劣汰,官方推出了新的加载函数 spl_autoload_register,无论在加载方面还是异常捕获方面都很友好,而且spl_autoload_register的使用扩展性还很好