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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看