我已創建三類。一類是從PDO擴展的db。其他兩個類從db類擴展。但問題是當我初始化這些子類的對象時,第二個對象被創建爲第一個對象的克隆。預先感謝您的幫助。錯誤時PDO類擴展
<?php
/** The Database Driver */
define('DB_DRIVER', 'mysql');
/** The name of the database */
define('DB_NAME', 'sample');
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', 'root');
/** MySQL hostname */
define('DB_HOST', 'localhost');
class db extends PDO
{
public function __construct()
{
echo "DB constructor called\n";
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
$dsn = DB_DRIVER . ":host=" . DB_HOST . ";dbname=" . DB_NAME;
parent::__construct($dsn, DB_USER, DB_PASSWORD, $options);
}
}
class Admin extends db
{
private $uid, $username, $password, $level, $name, $email;
public function __construct()
{
echo "Admin constructor called\n";
parent::__construct();
}
}
class Movie extends db
{
private $mid, $title, $slug;
public function __construct()
{
echo "Movie constructor called\n";
parent::__construct();
}
}
$adminObj = new Admin();
$movieObj = new Movie();
var_dump($adminObj);
var_dump($movieObj);
?>
下面是上述的輸出。 請注意輸出中顯示的對象類型。
Admin constructor called
DB constructor called
Movie constructor called
DB constructor called
object(Admin)#1 (6) {
["uid":"Admin":private]=>
NULL
["username":"Admin":private]=>
NULL
["password":"Admin":private]=>
NULL
["level":"Admin":private]=>
NULL
["name":"Admin":private]=>
NULL
["email":"Admin":private]=>
NULL
}
object(Admin)#2 (6) {
["uid":"Admin":private]=>
NULL
["username":"Admin":private]=>
NULL
["password":"Admin":private]=>
NULL
["level":"Admin":private]=>
NULL
["name":"Admin":private]=>
NULL
["email":"Admin":private]=>
NULL
}
當父:: __構建體($ DSN,DB_USER,DB_PASSWORD,$選項);在db類中被刪除的問題會消失。
如果您不滿意提出的方案和需要持久連接,那麼(好,我會建議它在任何情況下)根本不延長PDO和創建'db'類中PDO實例,而不是或通行PDO實例作爲Admin/Movie類構造函數的參數。 – LazyOne 2011-06-10 18:55:16