php 类的自动加载主要靠php函数 spl_autoload_register来实现,
在php代码运行中,发现没有的定义的类。
-
检查前面加载的代码中有没有spl_autoload_register函数,
没有spl_autoload_register函数,直接报错:
Fatal error: Uncaught Error: Class "Singwa" not found
有spl_autoload_register函数:通过调用spl_autoload_register(‘autoload’, true, true)函数的第一个参数中的函数完成include类文件,
如果 没有此类文件建则会报错。Warning: include(./UndefineClass.php): Failed to open stream: No such file or directory
Singwa.php
<?php
class Singwa
{
public function hello()
{
echo "hello world".PHP_EOL;
}
}
autoload.php
<?php
class Tree {
public function hello()
{
echo "hello tree".PHP_EOL;
}
}
spl_autoload_register("autoload",true,true);
/**
* 自定义类加载
* @param $className
* @return void
*/
function autoload($className='') {
//能获取到未定义的类名
echo "类名为".$className.PHP_EOL;
include "./{$className}.php";
}
$res = new Singwa();
$res->hello();
$tree = new Tree();
$tree->hello();
$res = new UndefineClass();
$res->hello();
autoload.php 和 Singwa.php在同一个目录
thinkphp5.1 中为什么加载extend目录下的文件不用命名空间,而加载extend下面的目录下面的文件却需要命名空间?
因为extent 是 注册自动加载类库目录 可以直接找到类文件,extent下面的目录的文件则需要命名空间 拼接文件路径才能找到 类文件