2011-04-02 50 views
3

我有一个用户认证系统,我目前正在编写。问题是,我不想为每个我想要使用该类的页面包含类x,y,z等。例如,这里是索引页:PHP - 避免每个页面包含所有内容?

///////// I would like to not have to include all these files everytime//////// 

include_once '../privateFiles/includes/config/config.php'; 

include_once CLASSES.'\GeneratePage.php'; 

include_once DB.'\Db.php'; 

include_once HELPERS.'\HelperLibraryUser.php'; //calls on user class 
////////////////////////////////////////////////////////////////////////////// 

$html = new GeneratePage(); 
$helper = new HelperLibraryUser("username","password","email"); 

$html->addHeader('Home Page',''); 

$html->addBody('homePage', 
'<p>This is the main body of the page</p>'. 
$helper->getUserEmail().'<br/>'. 
$helper->doesUserExists()); 

$html->addFooter("Copyright goes here"); 

echo $html->getPage(); 

正如你所看到的,有我需要包括每个页面上的几个文件,以及更多的类,我补充了更多的文件,我将不得不包括。我如何避免这种情况?

回答

3

您可以定义一个自动加载功能,例如:

function __autoload($f) { require_once "/pathtoclassdirectory/$f.php"; } 

这样,当PHP遇到一个参考一类是不知道,它会自动查找具有相同的名称文件类并加载它。

你可以明显在这里添加一些逻辑,如果你需要把不同类别在不同的目录...

+0

这会如何影响速度?我想它比指定类路径的速度慢? – johnyboy 2011-04-02 07:09:30

+0

噢,我通常把这个函数定义在一个常见的文件中,如Click提到... – awm 2011-04-02 07:09:38

+0

谢谢你们:awn和Click Upvote!我会按建议做:) – johnyboy 2011-04-02 07:12:15

2

建立一个叫做common.php文件,并把这些包括报表以及其他功能/代码,您需要这个文件中的每个文件(如数据库连接代码等)。然后,在每个文件的顶部简单地做到这一点:

<? 
require_once('common.php'); 

这将包括所有的文件,而无需将它们包括seperately。