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

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)

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.

Do not use global $dbh.

Just add a property to your DB class, for example protected $db and then put your PDO instance inside $this->db for you can use the $db var only inside the object. This is the basic way to use some kind of "Database Model" , where you can find plenty of tutorials through the web :)

For example :

public __construct($db_type = 'mysql', $host = 'my_server', $database = 'db_name', $user = 'my_user', $pwd = 'password') {
    $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;

    $dsn = $db_type.':host=' . $host . ';dbname=' . $database . '';

    try {
        $this->db = new PDO($dsn, $user, $pwd, $pdo_options);
    } catch (Exception $e) {
        'Unable to connect to database';
    }
}

And then make an instance of your object in the global scope, where you script uses it :

$db_manager = new DB('mysql','localhost','my_db','root','password');

And then your $db_manager will be able to use the public methods of your DB class

There you go..

class DB {

  protected $dbh;

  public function __construct() {   

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

  public function getFAQCats2Array() {  

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

      $s = $this->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);
    }
  }
}