您好我正在尝试访问从Database类中的DatabaseConnection类返回的pdo对象,但是我使用单例模式时遇到了困难。请帮助
class DatabaseConnection {
protected static $_instance = NULL;
public static $pdo;
private function __construct() {
try {
$this->pdo = new PDO ( 'mysql:host=' . Configuration::getConfiguration ( 'mysql/host' ) . ';dbname=' . Configuration::getConfiguration ( 'mysql/databaseName' ), Configuration::getConfiguration ( 'mysql/user' ), Configuration::getConfiguration ( 'mysql/password' ) );
} catch ( PDOException $e ) {
echo 'woops !connection to the server failed.' . $e->getMessage ();
}
}
public static function getConnectionInstance() {
if (! isset ( self::$_instance )) {
self::$_instance = new DatabaseConnection ();
}
return self::$_instance;
}
}/*end od DatabaseConnection*/
class Database implements DatabaseInterface {
public static function select($fields = array(), $table, $where = array())
{
$fields = '`' . implode ( '`,`', $fields ) . '`';
$fix = '';
$x = 1;
foreach ( $where as $tableField => $value ) {
$fix .= "`{$tableField}` = '{$value}'";
if ($x < count ( $where )) {
$fix .= ' AND ';
}
$x ++;
}
$sql = "SELECT {$fields} FROM `{$table}` WHERE {$fix} ";
if (DatabaseConnection::$pdo->prepare ( $sql )) {
echo 'prepared';
}
return false;
}
}
答案 0 :(得分:0)
$pdo
成员应该是实例成员,而不是类成员。仅将public static $pdo
更改为public $pdo
。然后,您可以通过
DatabaseConnection::getConnectionInstance()->pdo;