案例一:
//创建一个操作数据库的工具类,要求只链接一次数据库 class DaoMysql{ //定义需要的属性 //$mysql_link是数据库链接 private $mysql_link; // $instance是一个静态属性,表示DaoMysql的一个对象实例 private static $instance = null; //构造方法 将构造方法设置为私有 private function __construct($host,$user,$pwd){ $this -> mysql_link = @mysql_connect($host,$user,$pwd); } //写一个静态方法创建对象实例 public static function getSingleton($host,$user,$pwd){ //通过 getSingleton来创建对象 //进行判断如果$instance为空则创建一个对象实例不为空则直接返回$instance //instanceof 判断对象实例是否是一个类的对象 if(!self::$instance instanceof self){ self:: $instance = new self($host,$user,$pwd); } return self:: $instance; } //阻止克隆 private function __clone(){} } $dao1 = DaoMysql::getSingleton('localhost','root',''); $dao2 = DaoMysql::getSingleton('localhost','root',''); $dao3 = DaoMysql::getSingleton('localhost','root',''); $dao4 = DaoMysql::getSingleton('localhost','root',''); var_dump($dao1,$dao2,$dao3,$dao4);
案例二:
class Girl{ private $name; private $age; private $stature; private static $instance = null; private function __construct($name,$age,$stature){ $this -> name = $name; $this -> age = $age; $this -> stature = $stature; } public static function getGirl($name,$age,$stature){ if(!self::$instance instanceof self){ self::$instance = new self($name,$age,$stature); } return self::$instance; } private function __clone(){} } $girl1 = Girl::getGirl('小红',29,160); $girl2 = Girl::getGirl('小花',23,162); $girl3 = Girl::getGirl('小玲',26,165); var_dump($girl1,$girl2,$girl3);