douquanhui5735 2012-08-06 14:26
浏览 45
已采纳

PHP OOP连接到MYSQL(构造函数与传递实例)的效率

I've been wondering about the effiency of OOP connections. The example structure is shown below. Each class seperated by folder and class name. For example:

/mysql/mysql.class.php //holds general connect and disconnect functions
/mysql/query.class.php //holds all the queries made to the db (uses basic mysql ^ )
/library/application.class.php //holds all the algorithms (uses queries to db ^ )

When it comes to executing an algorithm, the application.class.php calls upon query.class.php (when it needs to query) which calls mysql.class.php for a connection.

Which one of these two ways is correct (if any or both)? Is there a simpler and more efficient way of doing this?

Here is the same way of doing two things (Which is more efficient??) :

require_once('/mysql/mysql.class.php ');
require_once('/mysql/query.class.php ');

$mysqlClass = new MYSQL();
$queryClass = new Query();

class Application {                
  public function getVar() {         
    $param = foo;         
    $db = $mysqlClass->connect(); //connection to mysql
    $queryClass->callsomequerymethod($db, $param); //pass the db connection to function
  } 
} 

VS

class Application {     
  private $db;      
  public function __construct(DatabaseConnection $db, QueryClass $queryclass){
    $this->db = $db;     
  }           
  public function getVar() {         
    $param = foo;         
    $db = $this->db;
    $queryclass->callsomequerymethod($db, $param);
  } 
} 
  • 写回答

1条回答 默认 最新

  • douzhuo5671 2012-08-06 14:29
    关注

    Can't comment on efficiency, but the second method would be better since the variables are neatly scoped within the class that uses them, as opposed to lying in the global namespace.

    A further modification I would make is move the require statements within the constructor so that those files are included only when the class that uses them (in your case Application) is instantiated.

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

报告相同问题?

悬赏问题

  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1