自动加载类
我在包含文件夹中创建了一个名为 Database.class.php 的数据库类。这是我的代码:
require_once 'includes/smarty/Smarty.class.php';
require_once 'includes/admin.functions.php';
function __autoload($class) {
require_once 'includes/'.$class.'.class.php';
}
try {
$db = Database::getInstance();
} catch (PDOException $e) { die('Error connecting to database.'); }
这段代码有什么问题吗?前 2 个包含工作正常,我只收到“未找到类数据库”错误。
自动加载仅在创建新对象时才起作用吗?如果是这样,单身人士有解决方法吗?或者我做错了什么?
谢谢!
编辑: 当手动包含时,它可以工作。所以这确实与自动加载有关..
I have created a Database class named Database.class.php in my includes folder. This is my code:
require_once 'includes/smarty/Smarty.class.php';
require_once 'includes/admin.functions.php';
function __autoload($class) {
require_once 'includes/'.$class.'.class.php';
}
try {
$db = Database::getInstance();
} catch (PDOException $e) { die('Error connecting to database.'); }
Is there anything wrong with this code? The first 2 includes works fine, I'm only getting a "class Database not found" error.
Does autoload only work when creating new object? If so, is there a workaround for singletons? Or am I doing something wrong?
Thanks!
EDIT:
When manually including, it works. So it's really related to the autoloading..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Smarty 使用
spl_autoload_register
。如果您有自己的自动加载函数,并且希望它们一起工作,则也必须使用spl_autoload_register
注册它。Smarty registers an autoload function with
spl_autoload_register
. If you have your own autoload function you must register it withspl_autoload_register
too if you want them to work together.