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

时间:2017-09-24 22:09:05

标签: php html css web autoload

我是一个新的PHP开发者,我在使用自动加载功能时遇到了不好的时间。这是错误。

EEE

它显示了类,但随后回显了一个错误。

这是自动加载功能。

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

这是索引文件

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");
}

1 个答案:

答案 0 :(得分:2)

您可以采取一些措施来追踪问题。尝试将自动加载功能更新为:

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;
    }
}