I have a class name DBConnection:
class DBConnection { public function __construct() {} public static function getConnection() { try{ $conn = new PDO('mysql:host='.HOST.'; dbname='.DATABASENAME.'; charset=utf8', USERNAME, PASSWORD); return $conn; }catch(PDOException $e){ echo("Connect to database failed"); } } } And a class name bookDA:
require_once("DBConnection.php"); require_once("../entity/book.php"); class bookDA { private $conn = DBConnection::getConnection();//This line didn't work public function getAll() { $bookList = array(); $stmt = $this->conn->prepare("SELECT * FROM booklist"); $stmt->execute(); while($result = $stmt->fetch(PDO::FETCH_ASSOC)) { $bookList[] = new book($result["bookId"], $result["bookName"], $result["bookPrice"]); } return bookList; } public function getByName($name) { $bookList = array(); $stmt = $this->conn->prepare("SELECT * FROM booklist WHERE LIKE :name"); $stmt->bindValue(":name", "%".$name."%", PDO::PARAM_STR); $stmt->execute(); while($result = $stmt->fetch(PDO::FETCH_ASSOC)) { $bookList[] = new book($result["bookId"], $result["bookName"], $result["bookPrice"]); } return bookList; } } i create a static method:"getConnection" inside class DBConnection, and in the class:"bookDA" i call it but it didn't work. So i try to put the line which didn't work outside the bookDA class and this work like a champ. Can anyone tell me why?