面向对象 PHP 程序中的自动加载问题

Autoloading Problem in Object-Oriented PHP Program

大家下午好。

过去 3 天,我一直在努力使用 PHP 的自动加载功能,该功能旨在简化和统一程序的 class 文件,所有文件都位于一个执行文件中。对于上下文,我目前正在从 this tutorial videos 学习 PHP 的 OOP 视角,不仅可以在大学做 PHP OOP 项目之前进一步了解 PHP 的 OOP 理解,还要自己尝试制作PHP程序,所以做ELI5的解决方法请给我。

根据我从以下视频中学到的知识:Video 1 and Video 2,我根据所学知识编写的自动加载代码似乎工作正常,但是,它给出了两个警告:

Warning: include(/classes/person.php): failed to open stream: No such file or directory in C:\xampp\htdocs\CollegeTimetableApp\includes\autoloader.php on line 12

Warning: include(): Failed opening '/classes/person.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\CollegeTimetableApp\includes\autoloader.php on line 12

并且,它给出了如下致命错误信息:

Fatal error: Uncaught Error: Class 'person' not found in C:\xampp\htdocs\CollegeTimetableApp\includes\index.php:33 Stack trace: #0 {main} thrown in C:\xampp\htdocs\CollegeTimetableApp\includes\index.php on line 33

我将包括 downloadable files 以便任何人与我一起检查和验证。

自动加载文件上的自动加载程序代码:

<?php

spl_autoload_register(function($className) {
    include str_replace("\","/","\classes").'/'.str_replace('\',"/",$className).'.php';
});

?>

索引文件的简单执行代码:

<?php

$person1 = new person();
$person1->SetName("Kai");
echo $person1->name;

?>

我的问题:出了什么问题,如何创建一个有效的自动加载功能,我的程序是否可以进行任何其他更正?

谢谢。

尝试将 $_SERVER['DOCUMENT_ROOT'] 添加到您的路径,以及该文件夹中包含您的应用程序的子文件夹。

<?php

spl_autoload_register(function($className) {
    $file = $_SERVER['DOCUMENT_ROOT']; // This is the folder you serve files from
    $file .= '/CollegeTimetableApp' // This is the folder in which your app lives
    $file .= str_replace("\", "/", "\classes"); 
    $file .= '/'; // Consider using DIRECTORY_SEPARATOR instead
    $file .= str_replace('\', "/", $className);
    $file .= '.php';
    include $file;
});

?>