我正在尝试自动加载PHP中的类,这些类存储在classes文件夹的子文件夹中。下面是目录和文件结构:
htdocs
SANDBOX
index.php
classes
app
app1.php
utlity
utility1.php以下是index.php的内容:
<!DOCTYPE HTML>
<html>
<?php
//autoload classes
# first attempt
spl_autoload_register(function($class) {
require_once 'classes/' . $class . '.php';
});
# second attempt
// spl_autoload_extensions(".php");
// spl_autoload_register();
//render stuff in browser
echo '<p>this is the test page</p><br>';
echo Utility1::greeting();
echo App1::greeting();
?>
</html>App1.php的内容如下:
<?php
namespace classes/app;
class App1
{
public static function greeting()
{
return 'app<br>';
}
}
?>下面是utility1.php的内容:
<?php
namespace classes/utility;
class Utility1
{
public static function greeting()
{
return 'utility<br>';
}
}
?>index.php中的尝试1和尝试2都没有成功地自动加载类。需要做哪些修改才能使自动加载与此文件结构一起工作?理想的自动加载方法将允许将来将更多的子文件夹添加到classes文件夹中,并且不需要修改自动加载代码。
发布于 2014-03-17 09:05:53
您的类位于命名空间中,当您在代码中访问它们时,需要提供正确的命名空间:
echo \classes\utility\Utility1::greeting();
echo \classes\app\App1::greeting();除此之外,你的自动加载器基本上看起来没问题。但是,您应该将参数转换为小写(或以正确的大小写命名文件),并将\替换为/ (以获得完全的操作系统互操作性)。
https://stackoverflow.com/questions/22445292
复制相似问题