PHP和PDO类的问题

Euj*_*Kim 5 php pdo class

我是OOP风格的PHP的新手,我也试图实现PDO.我在网上发现了这个很好的小类来处理数据库连接,但我不知道如何从另一个类访问它.这是代码:

  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 />";
      }  
    }
  }
Run Code Online (Sandbox Code Playgroud)

如何访问$db_handlePerson类中的变量?我是否必须在Person类中实例化变量?如果是这样,这是否意味着我将永远称之为$this->db_handle?我希望避免这种情况.(我仍然只对类的变量范围有一个非常基本的了解)

Mic*_*ski 5

有(至少)三种方法来处理这个问题.最便携,最常推荐的是"依赖注入",通过它将数据库句柄传递给你的类并将其__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);
Run Code Online (Sandbox Code Playgroud)

下一个方法是实例化$db_handle构造函数内部而不是传入它.这有点难以测试和调试.

class Person {
   public $db;
   public function __construct() {
      $this->db = PDO_DBConnect::getInstance();
   }
}
Run Code Online (Sandbox Code Playgroud)

最后,你可以调用$db_handleglobal,每当你在课堂上使用它.这可能是最难阅读和调试的.

class Person {
  public function __construct() {
    global $db_handle;
  }
  public function otherFunc() {
    global $db_handle;
    $db_handle; // do something
  }
}
Run Code Online (Sandbox Code Playgroud)