我的自动加载功能不起作用,但似乎 class 已加载 PHP

My autoload function doesnt work but it seems the class is loaded PHP

我是一名新的 PHP 开发人员,我在使用自动加载功能时遇到了麻烦。这是错误。

public class dog{ public function hey($var){ echo $var; } }
Fatal error: Uncaught Error: Class 'dog' not found in C:\xampp\htdocs\ebay\index.php:3 Stack trace: #0 {main} thrown in C:\xampp\htdocs\ebay\index.php on line 3

它显示 class 但随后回显错误。

这是自动加载功能。

require_once("config.php");
spl_autoload_register("my_auto_load");

function my_auto_load($class_name){
    $path = "classes";
    require_once($path.DS.$class_name.".php");
}

这是索引文件

require_once("config.php");
spl_autoload_register("my_auto_load");

function my_auto_load($class_name){
    $path = "classes";
    require_once($path.DS.$class_name.".php");
}

这是索引文件

<?php 
require_once("inc/autoload.php");
$dog= new dog();
$dog->hey("KLK");
?>

您可以采取一些措施来查明您的问题。尝试将您的自动加载功能更新为如下所示:

function my_auto_load($class_name){
  $path = "classes";

  $includeFilename = $path.DS.$class_name.".php";

  ?>
  Class: <?= $class_name; ?><br>
  Include Filename: <?= $includeFilename; ?><br>
  Include Filename Real Path: <?= realpath($includeFilename); ?><br>
  Current working directory: <?= getcwd(); ?><br>
  Does the include file exists? <?= file_exists($includeFilename) ? "Yes, it exists" : "No, it doesn't exist"; ?><br>
  <?php

  require_once($includeFilename);
}

这将显示您的自动加载功能是否为偶数 运行,如果为 运行,它实际尝试包含的文件是什么以及该文件是否存在。如果它正确地创建了文件路径并且该文件存在,那么您的问题可能出在其他地方。

我重新创建了您的项目,它似乎运行良好。这是我的目录结构:

./classes/dog.php
./inc/autoload.php
./index.php

index.php

<?php

require_once("inc/autoload.php");
$dog= new dog();
$dog->hey("KLK");

inc/autoload.php

<?php

spl_autoload_register("my_auto_load");
function my_auto_load($class_name){
    $path = "classes";

    $includeFilename = $path.'/'.$class_name.".php";

?>
  Class: <?= $class_name; ?><br>
  Include Filename: <?= $includeFilename; ?><br>
  Include Filename Real Path: <?= realpath($includeFilename); ?><br>
  Current working directory: <?= getcwd(); ?><br>
  Does the include file exists? <?= file_exists($includeFilename) ? "Yes, it exists" : "No, it doesn't exist"; ?><br>
<?php

    require_once($includeFilename);
}

classes/dog.php

<?php

class dog {
    public function hey($msg) {
        echo $msg;
    }
}