PDO连接不会在类之间移动

时间:2012-12-01 17:36:22

标签: php class pdo oop

class Group extends dbConnection { //Class for group, for ex. employe and employers.
    public $name;  // Name of group
    public $pdo;

    public function __construct ($name, dbConnection $pdo) {
    $this->pdo = $database->pdo;
    }

    public function getGroupList() {  
        try //                       FAULTY LINE BELOW \/\/\/\/\/\/\/
        {
          $pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //to catch exceptions

          $stmt = $pdo -> query('SELECT id, Name, Skills FROM '.$this->name); //sql query with group name
          $list = $stmt->fetchAll(PDO::FETCH_NUM); //fetch statement into array
          $stmt -> closeCursor();
          unset($stmt);
          return var_dump($list); //gives pure data
        }
        catch(PDOException $e) 
        {
          return 'There was some error: ' . $e->getMessage();
        }
    }

}

和dbConnect类:

  class dbConnection {
    public $pdo;
    public function __construct () {
        $this->dbConnect();
    }
    public function dbConnect () {
        if((count($_POST) == 6)&&($_GET['a'] == "connect")) {
            $host = $_POST['host'];
            $port = $_POST['port'];
            $username = $_POST['username'];
            $password = $_POST['password'];
            $database = $_POST['database']; 
            try{
                    $pdo = new PDO('mysql:host='.$host.';dbname='.$database.';port='.$port, $username, $password );
                    echo 'Connection successful!';
                    return $pdo;
            }
            catch(PDOException $e){
                    echo 'Error: ' . $e->getMessage();
            }   
        }
    }
}

执行:

$conn = new dbConnection;
$workers = new Group("workers", $conn);
$workers->getGroupList();

之后:“连接成功”我收到错误:

致命错误:在第14行的非对象上调用成员函数setAttribute()

我认为类Group不会从dbConnection获取$ pdo。我不知道我做错了什么。

1 个答案:

答案 0 :(得分:0)

更改(在dbConnect类中)

$pdo = new PDO('mysql:host='.$host.';dbname='.$database.';port='.$port, $username, $password );

$this->pdo = new PDO('mysql:host='.$host.';dbname='.$database.';port='.$port, $username, $password );

也改变以下

public function __construct ($name, $database) {
  $this->pdo = $database->pdo;
}

同样在Group课程中,请使用$this->pdo代替$pdo