doumi7861 2017-10-23 17:22
浏览 25
已采纳

PHP性能:“全局”关键字在功能上比“包含”更好吗?

Let's pretend I have a database.php file which contains a persistent access to the database.

<?php
$database = new PDO('mysql:host=xxx', "xxx", "xxx", array(
    PDO::ATTR_PERSISTENT => true
));
?>

Every time I want to query the database within a controller, what should I do?

1/ Use the global keyword to get my global $database variable

<?php

include '../app/config/Database.php';

function getLastOfTheWeek()
{
    global $database;
    $database->query('SELECT * FROM `xxx`');
    ...
}
?>

2/ Include database.php within the function

<?php

function getLastOfTheWeek()
{
    include '../app/config/Database.php';
    $database->query('SELECT * FROM `xxx`');
    ...
}
?>

3/ Give this man some doc, he needs it

Or both are evil anyway, and I should use another method.

  • 写回答

2条回答 默认 最新

  • dphw5101 2017-10-23 17:50
    关注
    1. Global state is bad.
    2. Repeatedly creating DB connections is bad.

    Good:

    $dbh = new PDO (...);
    
    function doSomething($dbh) {
      $dbh->query(...);
    }
    

    OK:

    class Something {
      protected $dbh;
    
      public function __construct($db_config) {
        $this->dbh = new PDO($db_config); // still bad
      }
    
      public function doSomething() {
        $this->dbh->query();
      }
    }
    

    God Tier:

    class Something {
      protected $dbh;
    
      public function __construct(PDO $dbh) {
        $this->dbh = $dbh;
      }
    
      public function doSomething() {
        $this->dbh->query();
      }
    }
    
    $dbh = new PDO(...);
    $s = new Something($dbh);
    $s->doSomething;
    

    See: http://www.phptherightway.com/#dependency_injection

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路