使用 spl_autoload_register 包含错误

Include error using spl_autoload_register

我的 php 代码中有一个奇怪的错误。 我这样使用 spl_autoload_register:

function load($class) {
    require 'class/' . $class . '.php';
}
spl_autoload_register('load');

然后在我的页面上,当我尝试加载 class 时,整个页面会再次加载。 这是我写的:

<?php include('inc/header.php'); ?>
<body>
<?php include('inc/nav.php'); ?>
[some html]
<?php load('Class'); ?>
[otherhtml]
<?php include('inc/footer.php') ?>

但是当我在我的本地服务器上尝试 运行 时(使用 xampp),整个页面再次被包含,它看起来像这样:

[header]
<body>
[nav]
[some html]
    [header]
    <body>
    [nav]
    [some html]
    [other html]
    [footer]
[other html]
[footer]

我遇到了一些 php 错误,主要是因为 header 被包含了两次:

A session had already been started - ignoring session_start().

Fatal error: Cannot redeclare load() (previously declared in C:...inc\header.php:2) in C:...inc\header.php on line 4

只有当 运行 在 xampp 时才会发生这种情况。我将所有内容上传到我的网络服务器,没有问题。两天前它工作正常,当我尝试使用 phpstorm.

安装作曲家时可能已经开始了

如有任何帮助,我们将不胜感激。 谢谢!

spl_autoload_register 的优点是不需要调用函数来包含 class XY 因为注册的自动加载器将在实例化 class XY 但没有实例化时被触发尚未宣布(包括)。

在上面的代码中,您首先声明加载函数,注册它,然后调用加载函数。

这是您的代码:

<?php include('inc/header.php'); ?>
<body>
<?php include('inc/nav.php'); ?>
[some html]
<?php load('Class'); ?>
[otherhtml]
<?php include('inc/footer.php') ?>

但是在使用 spl_autoload_register 时,我会使用以下内容:

<?php include('inc/header.php'); ?>
<body>
<?php include('inc/nav.php'); ?>
[some html]
new Load();
[otherhtml]
<?php include('inc/footer.php') ?>

区别在第5行

关于您遇到的两个错误:我完全同意mario的回复。