批改状态:合格
老师批语:类的自动加载只是进行的一种声明, 不可能代替require
我的理解:自动加载,就是当我们想引入一个或多个类时,在当前脚本中直接使用,会有一个自动加载器帮助我们自动引入类文件,并且被引入的类要具备两个条件:
类名必须和类文件名一致
(存在命名空间时)命名空间的名称要和当前类文件的路径一致
下面写一个目录,创建三个文件:

<?php// 1. 当前类的命名空间与当前类的文件路径对应起来namespace inc\lib;// 2. 类名必须与当前类文件名称相同class test1 {const NAME = '果冻';public static function show (){return __METHOD__;}}function test1 (){return '111';}
<?php// 1. 当前类的命名空间与当前类的文件路径对应起来namespace inc\lib;// 2. 类名必须与当前类文件名称相同class test2 {const HOBBY = 'fish';public static function show (){return self::HOBBY;}}function test2 (){return '222';}
<?php// 1. 当前类的命名空间与当前类的文件路径对应起来namespace inc\lib;// 2. 类名必须与当前类文件名称相同class test3 {const WORK = '学习';}function test3 (){return '333';}
<?php// 存在命名空间时的自动加载// 类的自动加载try{// $class_name 表示类名称 相当于 Demo::classspl_autoload_register(function($class_name){$path = str_replace('\\',DIRECTORY_SEPARATOR,$class_name);$file = __DIR__.DIRECTORY_SEPARATOR.$path.'.php';if (!(is_file($file) && file_exists($file)))throw new \Exception('不是文件名文件不存在');require $file;});}catch(Exception $e){die($e->getMessage());}// 别名use inc\lib\test1;use inc\lib\test2;use inc\lib\test3;// 输出echo test1::NAME,'<hr>';echo test2::HOBBY,'<hr>';echo test3::WORK,'<hr>';

引入类文件以后,便可以使用里面的函数,所以在使用函数前需要先new class
<?php// 存在命名空间时的自动加载try{spl_autoload_register(function($class){$path = str_replace('\\',DIRECTORY_SEPARATOR,$class);$file = __DIR__.DIRECTORY_SEPARATOR.$path.'.php';if (!(is_file($file) && file_exists($file)))throw new \Exception('不是文件名文件不存在');require $file;});}catch(Exception $e){die($e->getMessage());}// 别名use inc\lib\test1;use inc\lib\test2;use inc\lib\test3;// 引入类文件new test1;new test2;new test3;// 引入类文件中的函数echo inc\lib\test1(),'<br>';echo inc\lib\test2(),'<br>';echo inc\lib\test3(),'<br>';

当不存在命名空间时的类/函数自动加载
使用以下目录操作:

<?phpclass t1{}function t1(){return '111111111'.'<br>';}
<?phpclass t2{}function t2(){return '2222222222'.'<br>';}
<?phpclass t3{}function t3(){return '3333333333'.'<br>';}
<?php// 不存在命名空间时自动加载// 方法一:注册一个自动加载函数spl_autoload_register('meth');function meth ($class){$file = __DIR__.DIRECTORY_SEPARATOR.'some/sn/'.$class.'.php';require_once $file;}// 必须先new一下,引入类文件new t1;new t2;new t3;// 引入文件以后就可以使用里面的函数或方法了echo t1();echo t2();echo t3();// 方法二:使用自动加载器,传入回调函数/*spl_autoload_register(function($class){// 当存在命名空间的时候才能加上$path这段代码// $path = str_replace('\\',DIRECTORY_SEPARATOR,$class);$file = __DIR__.DIRECTORY_SEPARATOR.'some/sn/'.$class.'.php';if (!(is_file($file) && file_exists($file)))throw new \Exception('不是文件名文件不存在');require $file;});// 必须先new一下,引入类文件new t1;new t2;new t3;// 引入文件以后就可以使用里面的函数或方法了echo t1();echo t2();echo t3();*/

也许没有理解很好把,我现在的理解是,要实现自动加载,首先得实现自动加载这个文件,通过自动加载器来操作的话参数就是类名称,所以不管是要实现类加载还是函数加载,类文件中都要定义一个类(满足上述两个条件的类),当我们在当前脚本中使用类时就会通过自动加载器自动去搜索相应的类文件,然后引入,引入类文件以后,文件中的类或函数即可使用
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号