PHP - Avoid all the includes for every page?
I have a user authentication system that I am currently writing. Problem is, I don't want to have to include class x,y,z,etc for every page that I want to use that class for. For example, here is the index page:
///////// 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->getUserE开发者_如何学Pythonmail().'<br/>'.
$helper->doesUserExists());
$html->addFooter("Copyright goes here");
echo $html->getPage();
As you can see, there are a few files that I need to include on every page, and the more classes I add, the more files I will have to include. How do I avoid this?
You can define an autoload function, e.g.:
function __autoload($f) { require_once "/pathtoclassdirectory/$f.php"; }
This way, when php encounters a reference to a class it doesn't know about, it automatically looks for a file with the same name as that class and loads it.
You could obviously add some logic here if you need to put different classes in different directories...
Make a file called common.php
and put these include statements as well as any other functions/code that you need in every file (such as database connection code, etc) in this file. Then at the top of each file simply do this:
<?
require_once('common.php');
This will include all your files without having to include them seperately.
It is highly recommended not to use the __autoload() function any more as this feature has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged.. Now the spl_autoload_register() function is what you should consider.
<?php
function my_autoloader($class) {
include 'classes/' . $class . '.class.php';
}
spl_autoload_register('my_autoloader');
// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.class.php';
});
?>
精彩评论