dongli7236 2013-07-25 23: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-25 23: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部