为什么我的自动加载功能找不到特定类

发布于 2025-02-05 02:28:43 字数 916 浏览 3 评论 0原文

这是我的文件夹结构:

-classes
  -controller
     -ProductCtrl.php
  -model
  -view
-includes
  -components
  -autoload.inc.php
-pages
  -home.php
  -add-product.php
-index.php

这是我的自动加载器函数:

spl_autoload_register(function ($class) {
$str = str_replace("\\", "/", $class);
$file = $str.".php";

// if the file exists, require it
if (file_exists($file)) {
    require $file;
}
});

index.php

<?php
 require "includes/autoload.inc.php";

 //home page
 include "pages/Home.php";

现在,我可以从 home.php index.php ,但是每当我尝试访问 add-product.php 文件时,都会给我一个错误:

Fatal error: Uncaught Error: Class "classes\controller\ProductCtrl" not found in 
project_directory\pages\add-product.php

note :我在包含文件夹结构的每个类中都使用了名称空间。

here is my folder structure:

-classes
  -controller
     -ProductCtrl.php
  -model
  -view
-includes
  -components
  -autoload.inc.php
-pages
  -home.php
  -add-product.php
-index.php

this is my autoloader function:

spl_autoload_register(function ($class) {
$str = str_replace("\\", "/", $class);
$file = $str.".php";

// if the file exists, require it
if (file_exists($file)) {
    require $file;
}
});

Index.php

<?php
 require "includes/autoload.inc.php";

 //home page
 include "pages/Home.php";

Now I can access the ProductCtrl class from home.php which is in index.php, but whenever I try to accesss the same class in add-product.php file it gives me an error saying:

Fatal error: Uncaught Error: Class "classes\controller\ProductCtrl" not found in 
project_directory\pages\add-product.php

Note: I have used namespace in every class containing the folder structure.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

分开我的手 2025-02-12 02:28:43

该文件很可能不存在,因此该类仍然不确定。

如果指定基本路径,则更明确,并且可能已经解决了:

$file = __DIR__ . '///..///' . $str . ".php";
trigger_error("looking for file: '$file'");

还检查了“ auto-loader”处理哪些文件路径的通知日志(通过trigger_error记录,您稍后可以删除)。

The file most likely does not exist and therefore the class remains undefined.

If you specify a base-path, it is more explicit and might solve it already:

$file = __DIR__ . '///..///' . $str . ".php";
trigger_error("looking for file: '$file'");

Also check the error log for notices showing which file paths are processed by your auto-loader (by the trigger_error logging, you can remove it later).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文