【问题标题】:How to use file_exists with autoload如何将 file_exists 与自动加载一起使用
【发布时间】: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


【解决方案1】:

为了解决这些问题,我喜欢枚举一个匿名数组:

function myLoad($class) {
  foreach(['controllers', 'models', ''] as $prefix) {
    if(file_exists("application/$prefix/$class.class.php"))
      include_once("application/$prefix/$class.class.php");
  }
}

spl_autoload_register('myLoad');

请注意,如果您这样放置字符串,则在没有前缀的情况下您将有一个双斜杠,但这不应该有所作为。 我觉得这样更具可读性。

【讨论】:

  • 谢谢,我喜欢这个解决方案。双斜杠不会影响路径吗?
  • 如果您要给出系统命令的路径,系统将忽略双斜杠。如果您要从给定库中提供某些解析器函数的路径,那将是一个真正的问题
【解决方案2】:

使用循环是使其更简洁的方法之一。将所有可能性放入一个数组中,循环遍历数组,并在包含文件后返回。在这种情况下,找到的第一个项目就是将要使用的项目。

$paths = [
  'application/controllers/'.$class.'.class.php',
  'application/models/'.$class.'.class.php',
  'application/'.$class.'.class.php'
];

foreach($paths as $path) {
   if (file_exists($path)) {
      include_once($path);
      return;
   }
}

但是,我建议不要构建自己的自动加载器,而是查看 PSR-4 标准并使用 composer。

【讨论】:

    猜你喜欢
    • 2010-12-22
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 2017-01-07
    • 2020-09-13
    • 1970-01-01
    • 2012-06-21
    相关资源
    最近更新 更多