類是單例模式,對象方式傳入參數,如果參數過多是,使用形參容易混亂
class ObjectPdo { /** * 基本配置信息 * @var array */ private $config = array( 'dbms'=> 'mysql', //數據庫類型 'host'=> 'localhost',//數據庫主機名 'port'=> 3306, //數據庫端口 'dbName'=> 'im', //使用的數據庫 'user'=> 'root', //數據庫連接用戶名 'pass'=> 'root', //對應的密碼 'char'=> 'utf8', // 字符集 'long_conn'=>false, // 是否是長連接 ); // 數據連接 dsn private $dsn=""; // 定義私有屬性 private static $_instance = null; // 定義 靜態 pdo 在實例化的時候也可以使用靜態調用 private static $pdo=null; //初始化 private function __construct(){ } //私有化克隆方法 private function __clone(){ } //公共化獲取實例方法 public static function getInstance(){ //if (!(self::$_instance instanceof Object)) // 這個兩種方式都可以 if (self::$_instance === null) { self::$_instance = new self(); } return self::$_instance; } /** * 使用 $this->name 獲取配置 * @param string $name 配置名稱 * @return multitype 配置值 */ public function __get($name) { return $this->config[$name]; } public function __set($name,$value) { if(isset($this->config[$name])) { $this->config[$name] = $value; } } public function __isset($name) { return isset($this->config[$name]); } // 拼接dsn 連接字符串 private function str_dsn() { $this->dsn="$this->dbms:host=$this->host;port=$this->port;dbname=$this->dbName;charset=$this->char"; } // pdo 連接 public function conn() { if($this->long_conn==true) { $this->long_conn=array(PDO::ATTR_PERSISTENT => true); }else { $this->long_conn=array(); } try { // 實例化 PDO 對象 $this->str_dsn(); // 拼接dsn //$pdo = new PDO($this->dsn, $this->config['user'], $this->config['pass'],$this->config['long_conn']); // 如果使用靜態pdo 可以使用下面這種方法 if(self::$pdo === null) { self::$pdo = new PDO($this->dsn, $this->user, $this->pass,$this->long_conn); } echo '對象:'; var_dump(self::$pdo); echo "<br/>"; echo '參數 dbName 值: '.$this->dbName; //return $pdo; // 如果使用靜態pdo 可以使用下面這種方法 /*if(self::$pdo === null) { self::$pdo = new PDO($this->dsn, $this->config['user'], $this->config['pass'],$this->config['long_conn']); } return self::$pdo;*/ } catch (PDOException $e) { die ("Error!: " . $e->getMessage() . "<br/>"); } } }
調用示例
$singleton=ObjectPdo::getInstance(); $singleton->conn(); $singleton->dbName="test"; echo "<br/>"; $singleton->conn();
頁面顯示結果
對象:object(PDO)#2 (0) { } 參數 dbName 值: im 對象:object(PDO)#2 (0) { } 參數 dbName 值: test