尝试使用与singleton的数据库连接。 __constructor一直是私有的,并从静态函数返回实例。
class MyDbConn
{
protected $_conn;
protected $database;
protected $user;
protected $password;
protected $host = "localhost";
private static $instance;
private function __construct()
{
$this->db_conn = new PDO("mysql:host=$this->host;dbname=$this->database",$this->user,$this->password);
$this->db_conn->exec("set names utf8");
$this->_conn = $this->db_conn;
}
public static function returnInstance() {
if(self::$instance == null)
{
print "Object created!";
self::$instance = new self;
}
return self::$instance;
}
public function returnconnection(){
return $this->_connection;
}
}
现在我可以从MyDbConn :: returnInstance() - > returnconnection();
访问连接实例但是, 如何将用户详细信息和数据库名称传递给此构造函数?我不能做:: returnInstance($ username,$ password)或returnconnection($ username,$ password)。
请任何想法。
答案 0 :(得分:1)
您可以使用global
或正常的函数调用
<?php
class MyDbConn
{
protected $_conn;
protected $database;
protected $user;
protected $password;
protected $host = "localhost";
private static $instance;
private function __construct()
{
}
public static function returnInstance() {
if(self::$instance == null)
{
print "Object created!";
self::$instance = new self;
}
return self::$instance;
}
private static function initDatabase(){
$database = self::returnInstance();
global $config;
$database->_conn = new PDO("mysql:host={$config['host']};dbname={$config['database']}",$config['user'],$config['password']);
$database->_conn->exec("set names utf8");
return $database;
}
public static function returnconnection(){
try {
$db = self::initDatabase();
return $db->_conn;
} catch (Exception $ex) {
echo "Error Establishing Database Connection " . $ex->getMessage();
return null;
}
}
}
并传递这样的数据
// will be called from initDatabase using global keyword
$config = array('host' => 'localhost', 'database' => 'db name','user' => 'user here','password' => '');
$db = MyDbConn::returnconnection();
我不推荐使用Singleton,我建议使用Dependency Injection
答案 1 :(得分:0)
这是非常基本的问题。您将变量声明为protected,这意味着您只能在类中获取它们。这实际上非常好。要更改这些变量,您需要创建get和set方法,例如更改$ user write方法:
public function setUser($user)
{
$this->user = $user
}
public function getUser()
{
return $this->user;
}
//Then you need get your object via
$db = MyDbConn::returnInstance();
//set user
$db->setUser('john');
就是这样。而且,单例是调用反模式,因为它很难测试,它与全局变量非常相似,但并不好。