dongli7236 2013-07-26 07:09
浏览 306
已采纳

如何在此类中使用受保护变量而不是“全局”?

I have the following database query which works fine but in another question earlier, it was brought to my attention that I'm using a global, when it's not necessary. The reason for that was that I attempted to use a protected variable but being a new-comer to OOP, was unable to make it work.

Perhaps someone could show me how it should be done?

<?
class DB {

  public function __construct() {

    global $dbh;

    try {
      $dbh  = new PDO('mysql:host=localhost;dbname=main_db', 'my_user', 'my_pass');
      $dbh  ->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    }
    catch(PDOException $e) {
      echo $e->getMessage();
    }
  }

  public function getFAQCats2Array() {

    global $dbh;

    try {
      $q = '
            SELECT
                `id`        AS ci,
                `name`      AS n
            FROM
                `faqcat`;
      ';

      $s = $dbh->query($q);

      // initialise an array for the results
      $A = array();

      while ($r = $s->fetch(PDO::FETCH_ASSOC)) {
          $A[] = $r;
      }

      $s = null;
      return $A;
    }

    catch(PDOException $e) {
      echo  "Something went wrong fetching the list of FAQ categories from the database.
";
      file_put_contents(
          $_SERVER['DOCUMENT_ROOT']."/PDOErrors.txt",
          "



".$e->__toString(), FILE_APPEND);
    }
  }

  public function getFAQ($i, $f) {

      global $dbh;

       try {
        $q = '
            SELECT
                '.$f.'
            FROM
                faq
            WHERE
                id = ?
        ';

        $s = $dbh->prepare($q);
        $s->execute(array($i));
        //$s->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        $r = $s->fetch();

        return $r[$f];

      }

      catch(PDOException $e) {
        echo  "Something went wrong fetching the FAQ answer from the database.
";
        file_put_contents(
            $_SERVER['DOCUMENT_ROOT']."/PDOErrors.txt",
            "



".$e->__toString(), FILE_APPEND);

      }

  }

}

(There were other functions in the class using the same connection string in $dbh, but I've removed them for simplicities sake)

  • 写回答

3条回答 默认 最新

  • dtziv24262 2013-07-26 07:22
    关注

    You can simply strike the global $dbh! Globals are usally a very bad idea and make your code harder to mantain.

    In this case I recommend using a class property (which is kinda global, but ONLY in this class):

    class DB
    {
        protected $dbh;
    
        public function __construct()
        {
            $this->dbh = new PDO();
        }
    
        public function query()
        {
            return $this->dbh->query();
        }
    }
    

    I' ve stripped and simplifyed a lot of code here, but this should give you the idea of how class propertys work in general. You can also read a lot about this on the PHP.net Manual.

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

报告相同问题?

悬赏问题

  • ¥15 SQL Server下载
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求