【发布时间】:2018-07-31 10:40:30
【问题描述】:
我正在尝试使用 spl_autoload_register 函数来自动加载我的类。我已经让它工作了,但仍然收到大量这样的警告消息:“警告:include_once(application/models/controller.class.php):无法打开流:没有这样的文件或目录...”
我知道我需要使用 file_exists 方法以某种方式解决此问题,但不确定如何将其包含在我的代码中:
<?php
function myLoad($class) {
include_once('application/controllers/'.$class.'.class.php');
include_once('application/models/'.$class.'.class.php');
include_once('application/'.$class.'.class.php');
}
spl_autoload_register('myLoad');
new controller();
?>
我把它改成了这个,它现在可以工作了,但是有没有更简单/更简洁的方法来做到这一点?好像有点重复
function myLoad($class) {
if (file_exists('application/controllers/'.$class.'.class.php')){
include_once('application/controllers/'.$class.'.class.php');
}
if (file_exists('application/models/'.$class.'.class.php')){
include_once('application/models/'.$class.'.class.php');
}
if (file_exists('application/'.$class.'.class.php')){
include_once('application/'.$class.'.class.php');
}
}
spl_autoload_register('myLoad');
【问题讨论】:
-
你知道
if()指令吗?在include_once之前使用它。 -
是的,我明白这一点,但我需要为每个单独的包含语句执行此操作吗?还是有更简单的方法一次完成所有这些?
-
由于您的路径各不相同,因此最好为每个路径都这样做。
-
是的,您必须检查所有替代文件是否存在
-
啊,好的。谢谢
标签: php require file-exists spl-autoload-register