douzhou7124 2016-04-03 11:17
浏览 32
已采纳

一个单独的PHP类初始化文件[关闭]

This is the first time I'm doing a project in complete OO style. My classes look very messy. I found myself doing require_once on a bunch of class files and creating new instances of classes. So I put all the requiring and creating instances into a separate file (init.php) like so:

<?php

require_once 'resources/config.php';
require_once 'classes/db.php';
require_once 'classes/auth.php';
require_once 'classes/msg.php';
require_once 'classes/validate.php';
require_once 'classes/view.php';
require_once 'functions/misc.php';

//DB connection
$db = new DB(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$dbConnection = $db->connect();

$msg_class = new Msg();
$validate = new Validate($dbConnection);

$msg_strings[] = array();

$view = new View($dbConnection);

?>

Now I'm just doing require_once on this file.

And I don't use the View class in a few pages. So is it a bad practice and not good for performance to create instances of a class if I'm not going to use it?

  • 写回答

1条回答 默认 最新

  • dongwei5794 2016-04-03 11:28
    关注

    The best practice is generally to use an autoloader, PHP provides an excellent autoloader for this purpose - SPL autoloader : http://php.net/manual/en/function.spl-autoload-register.php

    You can create a callback which will automatically be called by PHP when a class is not found, in this callback you can require / include the folder path where PHP will search for your classes, you can also register multiple autoloaders which will be called in the order they are defined, example below -

    function auto_loader($classname) {
        //search in the classes folder for a class file.
        include 'classes/' . $classname . '.php';
    }
    
    function auto_load_somethingelse($class){
      //include here
    }
    
    //register the autoloaders
    spl_autoload_register('auto_loader');
    spl_autoload_register('auto_load_somethingelse');
    

    Place this at the top of your file where you have called your init.php file and the autoloader will be called whenever it finds a class that needs to be auto-loaded.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题