我的php代码中有一个奇怪的错误。我以这种方式使用spl_autoload_register:
function load($class) {
require 'class/' . $class . '.php';
}
spl_autoload_register('load');
然后在我的页面上,当我尝试加载类时,整个页面会再次加载。这是我写的:
<?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错误,主要是由于标头包含两次:
会话已启动 - 忽略 session_start()。
和
致命错误:无法重新声明 load()(之前在 C:...inc''header.php:2) in C:...inc''header.php 在第 4 行
这只发生在 xampp 上运行时。我将所有内容上传到我的网络服务器,没有问题。两天前它工作正常,当我尝试使用 phpstorm 安装作曲家时可能已经开始了。
任何帮助将不胜感激。谢谢!
> spl_autoload_register 的优点是无需调用函数来包含类 XY,因为如果一个实例化类 XY 但尚未声明(包含),将触发注册的自动加载器。
在上面的代码中,您首先声明 load 函数,注册它,然后调用 load 函数。
这是您的代码:
<?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 行。
关于你遇到的两个错误:我完全同意马里奥的回答。