<?php
class Student
{
/*
* 设计模式之
* 单例模式
* 三私有,一公有,静态
*/
/* 私有化构造方法和克隆方法 */
/* 可以使用final定义构造方法,防止继承后改变私有 */
/* 可以将protected设置private */
final protected function __construct() {}
protected function __clone() {}
/* 私有一个静态的属性,用于判断是否实例化 */
protected static $foo = null;
/* 定义一个公有静态方法供外部调用
其实这方法把控了实例化的权利 */
public static function ins()
{
/* 为空时,类没有被实例化过
所以实例化自己
也可以使用is_null()方法 */
if (self::$foo === null) {
self::$foo = new self();
}
/* 否则返回自身 */
return static::$foo;
}
}
/* 无法使用new来实例化对象 */
//$s1 = new Student();
//$s2 = new Student();
/* 将实例化的权利交给ins() */
$s1 = Student::ins();
$s2 = Student::ins();
/* 所实例化的对象是相同的 */
if ($s1 === $s2) {
echo 'same';
} else {
echo 'not same';
}