PHP-避免每个页面都包含所有内容?

PHP-避免每个页面都包含所有内容?,php,Php,我目前正在编写一个用户身份验证系统。问题是,我不想为我想使用该类的每个页面都包含类x、y、z等。例如,以下是索引页: ///////// 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

我目前正在编写一个用户身份验证系统。问题是,我不想为我想使用该类的每个页面都包含类x、y、z等。例如,以下是索引页:

///////// 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();
//我不希望每次都包含所有这些文件////////
include_once'../privateFiles/includes/config/config.php';
包括_once类。“\GeneratePage.php”;
包括_once DB.'\DB.php';
包括_once HELPERS.'\HelperLibraryUser.php'//对用户类的调用
//////////////////////////////////////////////////////////////////////////////
$html=new GeneratePage();
$helper=newhelperlibraryuser(“用户名”、“密码”、“电子邮件”);
$html->addHeader('主页','');
$html->addBody('homePage',
“这是本页的主体部分。”。
$helper->getUserEmail()。“
”。 $helper->doesUserExists()); $html->addFooter(“版权归此处”); echo$html->getPage();

正如您所看到的,每个页面上都需要包含一些文件,我添加的类越多,需要包含的文件就越多。如何避免这种情况?

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

function __autoload($f) { require_once "/pathtoclassdirectory/$f.php"; }
这样,当php遇到对它不知道的类的引用时,它会自动查找与该类同名的文件并加载它


如果需要将不同的类放在不同的目录中,显然可以在这里添加一些逻辑…

创建一个名为
common.php
的文件,并将这些include语句以及您需要的任何其他函数/代码放在该文件的每个文件中(如数据库连接代码等)。然后在每个文件的顶部执行以下操作:

<? 
require_once('common.php');

强烈建议不要再使用_autoload()函数,因为从PHP 7.2.0开始,此功能已被弃用。非常不鼓励依赖此功能。。现在,SPLAutoLoad注册函数()函数是您应该考虑的。

    <?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';
    });
    ?>


这对速度有何影响?我想这比显式声明类路径要慢,对吗?哦,我通常把这个函数定义放在一个公共文件中,就像刚才提到的Click…谢谢大家:awn和Click Upvote!我会按建议去做:)我怀疑速度会是个问题。计算出一个类需要加载只需要很少的计算量,而实际加载并没有什么不同。(尚未对其进行基准测试,但…)这里的优点是根本不加载不必要的类;不需要跟踪哪些页面需要什么。太好了!这个函数以及Click Upvote提到的方法正是我想要的。