web开发之-PHP自动加载
有的时候我们会初始化某个类文件,但是,这个类文件可能我们忘记引入了,那么就会报错,有没有什么办法可以解决这个问题呢?这就是自动加载的功能,看如下文件结构:


config.class.php
<?php
class Config{
public function __construct(){
echo "我是config配置文件".PHP_EOL;
}
}
?>
index.php
<?php
class MyLoader{
public static function loadClassFun($class){
echo $class.PHP_EOL;
$classPath = getcwd().DIRECTORY_SEPARATOR."inc".DIRECTORY_SEPARATOR."".strtolower($class).".class.php";
if(is_file($classPath)){
require_once $classPath;
}
}
}
spl_autoload_register(array("MyLoader","loadClassFun"));
$config = new Config();
?>
以上内容输出如下:
Config
我是config配置文件
注:实现自动加载,我们需要使用系统内置的spl_autoload_register函数来进行定义,如上面的:spl_autoload_register(array("MyLoader","loadClassFun"))。DIRECTORY_SEPARATOR是PHP提供的系统路径分割符,因为在linux和windows系统中,路径分割符是不一样的,在windows中为\,而在linux中为/,比如我们有一个路径信息,a文件夹中有一个b文件夹,那么在windows中路径为:a\b,而在linux中为a/b,所以,这个DIRECTORY_SEPARATOR会依据程序所运行的系统,自动决定使用哪个!
可以这样理解,当我们new 一个类的时候,比如上面的new Config(),这时候,就会自动调用MyLoader类中的loadClassFun的静态方法,所以,我们就会看到$class的变量为自动传过来的类名,我们在这个方法里进行小写转换,并拼接路径,使用之前讲过的require方法,就把这个类文件加载过来了,实例的时候就不会报错!
相关推荐
-
「PHP」MVC框架是什么?为什么要用它2025-02-25 00:25:41
-
如何用PHP写一个比较安全的API系统(实现)2025-02-25 00:19:49
-
php 解析url获取相关信息2025-02-25 00:15:37
-
mysql命令总结和PyMysql2025-02-25 00:11:35
-
MySQL特性:深入理解ICP2025-02-25 00:11:07