【问题标题】:Unable to find class, even though autoloader has loaded the file无法找到类,即使自动加载器已加载文件
【发布时间】:2019-09-14 02:50:15
【问题描述】:

所以我有一个反映我的命名空间结构的目录。自动加载器正在正确加载包含我的类的文件。 use 子句使用别名指定正确的类。尽管如此,PHP 仍表示它无法找到该类。我传统上不使用名称空间,因为这总是发生在我身上。但我试图强迫自己使用良好的做法。所以,我在这里尝试了解为什么我不能让它工作。

我已经检查过自动加载器实际上已经加载了文件。我检查了自动加载器使用的路径是否正确。

我的课程文件:

<?php
namespace classes\helpers\core_helper;

class core_helper
{


  public static function create_arg_pairs($arguments)
  {
  .....
  }


}//end core_helper


?>  

我的主应用程序文件:

<?php

ini_set("display_errors", "1");

define('AUTH_ROOT', dirname(__FILE__));

use classes\helpers\core_helper as hlpr;


function autoloader($class)
{

  if(require_once AUTH_ROOT.'/'.str_replace('\\','/',$class).'.php');

}
spl_autoload_register('autoloader');

......

$temp = explode("/", substr($path['path'], 1));
//get the controller
$contoller = strtolower(array_shift($temp));
//get the method
$method = strtolower(array_shift($temp));

$argArray = hlpr::create_arg_pairs($temp);


?>  

产生的错误是:

致命错误:未捕获的错误:类 'classes\helpers\core_helper' 不是 在 /var/www/html/auth/index.php:51 中找到堆栈跟踪:#0 {main} throw 在 /var/www/html/auth/index.php 第 51 行

但是我知道包含该类的文件已加载,因此将正确的命名空间传递给自动加载器,并将其正确转换为正确的路径。那为什么我看不到课程呢?

【问题讨论】:

  • “我知道包含该类的文件已加载”你怎么知道这个?
  • 你可能需要在使用语句之前调用自动加载器

标签: php namespaces autoloader


【解决方案1】:

说出来

namespace classes\helpers\core_helper;

然后

class core_helper

你告诉系统你的实际班级是classes\helpers\core_helper\core_helper。我希望你真正想要的是namespace classes\helpers;

【讨论】:

  • 啊,我现在明白了。非常感谢。我将命名空间更改为 classes\helpers,现在可以按预期工作,感谢您的帮助和耐心。
  • 对于可能遇到此问题的其他任何人,我的错误在于认为使用 use 保留字时调用了自动加载器,将命名空间和类名传递给自动加载器。显然,自动加载器在类访问时被调用,类名是派生的,然后是命名空间。在我的例子中,这意味着类名出现了两次,因为它已经是命名空间的一部分。我希望我对顿悟的解释能帮助其他发现自己遇到这个问题的人。再次感谢 Greg 的回答和指导。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-21
  • 2014-05-29
  • 2020-05-05
  • 2017-10-12
相关资源
最近更新 更多