<?php
/**
* 应用场景:
* 数据库连接这种比较费资源的操作;
* 我们希望整个应用只实列化一次
*
* 结构:
* 4私1公
* 私有化构造方法:防止使用 new 创建多个实列
* 私有化克隆方法: 防止clone多个实列
* 私有化重建方法:防止反序列化
* 私有化静态属性:防止直接访问存储实列的属性
*/
class Signle1
{
public static $instance = null;
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return static::$instance;
}
public function __construct()
{
}
public function __clone()
{
}
public function __wakeup()
{
}
}
$obj = Signle1::getInstance();
$obj2 = new Signle1();
$obj3 = clone $obj2;
$obj4 = unserialize(serialize($obj));
var_dump($obj);
echo '<hr>';
var_dump($obj2);
echo '<hr>';
var_dump($obj3);
echo '<hr>';
var_dump($obj4);
echo '<hr>';
class Db2
{
private static $instance = null;
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* 防止 new 多个实列
* Db2 constructor.
*/
private function __construct()
{
}
/**
* 防止clone 多个实列
*/
private function __clone()
{
}
/**
* 防止反序列化
*/
private function __wakeup()
{
}
}
var_dump(Db2::getInstance());
echo '<hr>';
var_dump(Db2::getInstance());
运行代码可以看到 代码Signle1类实列的句柄是不一样的,
而Db类这两个句柄都是5,一直是一个实列。