<?php
header('Content-type:text/html;charset=utf-8');
class Student{
//私有的静态的对象;
private static $obj = NULL;
private $name;
private $age;
private $sex;
//私有的克隆方法,防止类外克隆对象
private function __clone(){}
//私有的构造方法
private function __construct($arr){
$this->name = $arr['name'];
$this->age = $arr['age'];
$this->sex = $arr['sex'];
}
//公共的静态的创建对象的方法 当前对象 instanceof 类名 :表示判断当前对象是否是当前类的的对象
public static function GetInstanceof($arr){
if (!self::$obj instanceof self) {
self::$obj = new self($arr);
}
return self::$obj;
}
}
$arr = array(
'name' => '李柳',
'age' => 20,
'sex' => '女',
);
$obj =Student::GetInstanceof($arr);
var_dump($obj);
//数据库类实例应用
//数据库连接方式2:单例的数据库类(工具类)Db.class.php
<?php
header('Content-type:text/html;charset=utf-8');
//创建单例的数据库类(工具类)
class Db{
private static $obj = NULL;
private $db_host;
private $db_user;
private $db_pass;
private $db_name;
private $charset;
private function __construct($arr){
$this->db_host = $arr['db_host'];
$this->db_user = $arr['db_user'];
$this->db_pass = $arr['db_pass'];
$this->db_name = $arr['db_name'];
$this->charset = $arr['charset'];
$this->ConnectDb(); //连接mysql服务器的方法名
$this->SelectDb(); //选择数据库的方法名
$this->SetCharset(); //设置字符集的方法名
}
private function __clone(){} //防止类外克隆对象;
//类内创建对象
public static function getIntanceof($arr){
if (!self::$obj instanceof self) {
//如果对象不存在,则创建对象
self::$obj = new self($arr);
}
return self::$obj;
}
//创建私有的连接数据库的方法
private function ConnectDb(){
if (!@mysql_connect($this->db_host,$this->db_user,$this->db_pass)) {
die(mysql_error());
}
}
//创建私有的选择数据库的方法
private function SelectDb(){
if (!mysql_select_db($this->db_name)) {
die("选择数据库{$this->db_name}出错!");
}
}
//创建私有的设置字符集方法
private function SetCharset(){
mysql_query("set names {$this->charset}");
}
}
$arr = array(
'db_host' => 'localhost',
'db_user' => 'root',
'db_pass' => 'admin',
'db_name' => 'php9',
'charset' => 'utf8'
);
$obj1 = Db::getIntanceof($arr);
var_dump($obj1);