PHP and PDO Question

I am very new to PHP style with OOP and I am also trying to implement PDO. I found this cute little class online that handles a database connection, however I have no idea how to access it from another class. Here is the code:

  class PDO_DBConnect {
    static $db ;
    private $dbh ;
    private function PDO_DBConnect () {
        $db_type = 'mysql';  //ex) mysql, postgresql, oracle
        $db_name = 'postGal';
        $user = 'user' ;
        $password = 'pass' ;
        $host = 'localhost' ;
        try {
            $dsn = "$db_type:host=$host;dbname=$db_name";
            $this->dbh = new PDO ( $dsn, $user, $password);
            $this->dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
            $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch ( PDOException $e ) {
            print "Error!: " . $e->getMessage () . "\n" ;
            die () ;
        }
    }

    public static function getInstance (  ) {
        if (! isset ( PDO_DBConnect::$db )) {
            PDO_DBConnect::$db = new PDO_DBConnect ( ) ;
        }
        return PDO_DBConnect::$db->dbh;
    }
  }

  $db_handle = PDO_DBConnect::getInstance(); 

    class Person 
  {
    function __construct()
    {
      $STMT = $db_handle->prepare("SELECT title FROM posts WHERE id = ? AND author = ? LIMIT 20");
      $STMT->execute(array('24', 'Michael'));

      while ($result = $STMT->fetchObject()) 
      {
        echo $result->title;
        echo "<br />";
      }  
    }
  }

How to access a variable $db_handleinside the Person class? Should I create an instance of a variable inside the Person class? If so, does this mean that I will always call him $this->db_handle? I was hoping to avoid this. (I still have only a basic understanding of the scope of variables with classes)

+5
source share
3 answers

( ) . " ", __construct() . $this->db, .

class Person {
  // Member to hold the db handle
  public $db;

  public function __construct($db_handle) {
    // Assign the handle to a class member variable in the constructor
    $this->db = $db_handle;
  }
  public function otherFunc() {
    $this->db; // do something
  }
}

$person = new Person($db_handle);

$db_handle , . .

class Person {
   public $db;
   public function __construct() {
      $this->db = PDO_DBConnect::getInstance();
   }
}

, $db_handle global , . , , .

class Person {
  public function __construct() {
    global $db_handle;
  }
  public function otherFunc() {
    global $db_handle;
    $db_handle; // do something
  }
}
+5

Injection of Dependency:

$steve = new Person($db_handle);

, , , . , $dbh = $this->db_handle;, , , .

+3

Person ( , ), ( , , , ), . :

class Person
{
    function __construct($db_handle)
    {
        // ... your existing code

:

$person = new Person($db_handle);

$this->db_handler .

+3

All Articles