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.

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

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?