我有一个类Connection,它有一个对象$ db_connection(一个PDO对象)。然后我有一个具有Connection对象的Consultant连接。我想通过类Consultant的方法访问$ db_connection对象的方法。我试过这个:
$statement=$this->connection->db_connection->prepare($sqlQuery);
我有一个错误,说我试图获得非对象的属性。
连接类代码:
require('config.php');
class Connection{
public $db_connection;
public function __construct(){
try{
$this->db_connection = new PDO("mysql:host=".host."; dbname=".db_name,user,pass);
$this->db_connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$this->db_connection->exec("SET CHARACTER SET ".character_set);
}
catch(Exception $e){
echo "<br>Error at line:".$e->getLine()."<br>";
}
}
}
班级顾问代码:
require("Connection.php");
class Consultant{
private $connection;
function __construct(){
$connection = new Connection();
}
public function getAllProducts(){
$sqlQuery = "SELECT * FROM PRODUCTS;";
$statement=$this->connection->db_connection->prepare($sqlQuery); //HERE IS THE ERROR LINE!!!!!!!!
$statement->execute(array());
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
$this->db_connection = NULL;
return $result;
}
答案 0 :(得分:0)
简而言之,在Consultant类中,您需要将$ connection作为类中的true属性。
class Consultant{
private $connection;
function __construct(){
// $connection = new Connection();
//**** Answer *****
$this->connection = new Connection();
}
public function getAllProducts(){
$sqlQuery = "SELECT * FROM PRODUCTS;";
$statement=$this->connection->db_connection->prepare($sqlQuery);
......
}