前言
习惯了框架的使用,最基础的东西在记忆中慢慢逝去,自己写了个类,都无法调用,不是文件找不到,就是语法错误,因为最根本的原因在于
include 'filename.php'
都没使用,O(∩_∩)O哈哈~
一、使用函数加载
1.1新建一个 bootstrap.php
文件
1.2在bootstrap.php
中使用spl_autoload_register
spl_autoload_register(function ($class) {
$file = str_replace('\\', '/', $class) . '.php';
require $file;
});
1.3在启动页面加入 include 'bootstrap.php'
1.4最终效果及目录如下:

二、使用面向对象的方式加载(逼格比第一种方式高点而已)
2.1新建一个 bootstrap.php
文件
2.2在bootstrap.php
中使用class
方式
class Bootstrap
{
public static function boot()
{
spl_autoload_register([new self,"autoload"]);
}
public function autoload($class)
{
$file = str_replace('\\', '/', $class) . '.php';
require $file;
}
}
Bootstrap::boot();
2.3在启动页面加入 include 'bootstrap.php'
2.4最终效果及目录如下:

三、composer
方式(建议★★★★★)
3.1查看环境已经安装composer
。
composer

3.2 初始化一个composer
的配置文件,
composer init //一直enter

3.3 在配置文件中增加自动加载
{
"name": "administrator/new",
"authors": [
{
"name": "zlz112",
"email": "7708720@qq.com"
}
],
"autoload": {
"psr-4": {
"Api\\": "Api" //如果目录是小写或者更改名称,此处也要小写和更改
}
},
"require": {}
}
3.4 使用composer install
安装,生成配置文件夹
composer install
composer update //如果后面更换配置文件名,使用更新命令
3.5在启动页面加入 include 'vendor/autoload.php'

网友评论