【发布时间】:2013-09-09 10:56:55
【问题描述】:
我正在重写我的很多旧的肮脏的意大利面条代码,目前正在尝试掌握类、函数并围绕 MVC 模型松散地重建我的网站。
但是,我无法让我的标题模板包含,以引用由我的主配置文件自动加载的用户帐户详细信息,我认为我错过了一个非常重要的步骤。
错误信息是Fatal error: call to member function is_loggedin() on a non-object...,所以我猜测在template.class.php 中执行的包含无法访问account.class.php 函数。
更新:在 header.tpl.php 中执行 var_dump(get_included_files()) 表明 account.class.php 和 template.class.php 都包含(按此顺序)。我还尝试在 header.tpl.php 的顶部手动包含 account.class.php 以查看它是否会产生任何影响......它没有。帮助:(
我还应该注意,我可以毫无问题地从 index.php 调用 $_account->is_loggedin()。 Jst 不在包含的文件 header.inc.php 中。
我可能会遇到这一切都错了,所以如果有人可以提供一些指示,下面是我的代码的简化编写:
index.php
<php require 'defaults.php'; ?>
<html>
<head>
...
</head>
<body>
<?php $_template->load('header'); ?>
....
</body>
defaults.php
session_start();
// define path settings
// connect to database, memcache
// lots of other stuff....
//autoloader for functions
spl_autoload_register(function ($class) {
if (file_exists(CLASS_PATH.DS.$class.'.class.php'))
{
include CLASS_PATH.DS.$class.'.class.php';
}
});
$_account = new account(); // autoload user account stuff
$_template = new template(); // autoload templates
account.class.php
class account
{
private $db;
public function __construct($db) {
$this->db = $db;
}
public function is_loggedin() {
// do various session checks
}
}
template.class.php
class template
{
public function load($template)
{
if (file_exists(TPL_PATH.DS.$template.'.tpl.php'))
{
include TPL_PATH.DS.$template.'.tpl.php';
}
}
}
header.tpl.php
<div id="header">
<?php if($_account->is_loggedin() == true): ?>
<p>logged in</p>
<?php else: ?>
<p>not logged in</p>
<?php endif; ?>
【问题讨论】:
-
在使用该类之前,请执行
var_dump(get_included_files());以查看您的类文件是否包含在内。您描述的错误通常来自不存在的类。要么您的自动加载器注册失败,要么包含类文件的某处存在错误。一步一步调试它,你应该离解决问题更近了一点。 -
您的应用程序模型可以改进,您的代码风格有点像 PHP4 的老式风格,但是对于类、模式和模型的新手来说,这是一个良好的开端。作为提示,我会将 template.class.php 中的
if子句扩展为else { throw new Exception("include file not found"); }之类的东西 - 以查看该文件是否真正包含在内。 -
是的,不幸的是,我很老派,但我试图打破这个习惯。我已将异常添加到 defaults.php 中的 autoloaer 和 template.class.php,但我没有收到任何错误。该模板肯定包含在内,因为当我访问索引时,我看到了标题模板的内容....但除此之外我不确定
-
我将从
var_dumping$_account开始,就在引发错误的行之前,这样您就可以准确地看到它认为变量是什么。
标签: php class autoloader