PHP自动加载机制

守給你的承諾、 提交于 2020-03-11 13:18:51

一、require / include
最初的文件加载机制是require/include把一个文件加载进来,但是随着开发规模的增大,复杂性也越来越高,可能造成遗漏或者冗余,因此在PHP5版本进入自动加载机制(autoload)

require("/var/www/Person.php")
$per = new Person()

//或者
include("/var/www/Person.php")
$per = new Person()

二、PHP 自动加载函数 __autoload()
在new一个class时,PHP系统如果找不到这个类,就会去自动调用本文件中的__autoload($classname)方法,去require对应路径的类文件,从而实现自动lazy加载,但是现在已经弃用。
首先同目录新建一个Person类

<?php
class Person {
    public function hello(){
        echo "hello";
    }   
}
<?php

function __autoload($classname) {
    $classpath="./".$classname.'.php';
    if (file_exists($classpath)) {
        require_once($classpath);
    } else {
        echo 'class file'.$classpath.'not found!';
    }   
}

$p = new Person();
$p->hello();

执行时会提示 PHP Deprecated:  __autoload() is deprecated, use spl_autoload_register() instead

三、SPL Autoload Register
可以注册任意数量的自动加载器,当然也可以单个加载,但是这样做,对于大型项目来说,极其不方便管理

spl_autoload_register(function($className){
    if (is_file('./' . $className . '.php')) {
        require './' . $className . '.php';
    }                   
});                     

$p = new Person();
$p->hello();

输出 hello

正确的做法如下:
①定义一个loader加载器

<?php
class Loader {
    public static function autoload($classname) {
        $file = "./".$classname.".php";

        if (file_exists($file)) {
            include $file;
        } else {
            echo 'class file'.$classname.'not found!';
        }   
    }   
}

② 注册加载器

//引入加载器
include "./Loader.php";

spl_autoload_register("Loader::autoload", true, true);

$p = new Person();
$p->hello();

输出hello
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!