php单例模式入门例子
时间:2021-07-01 10:21:17
帮助过:17人阅读
- class mysql{
- privete static $instance ;//保存实例
- //构造函数声明为private, 防止直接创建对象
- privete function __construct(){
- // 实例化
- }
- //单例方法, 判断是否已经实例化,只实例化一次
- public static function getInstance (){
- if(!isset( self::$instance )){
- self ::$instance = new self();
- }
- return self:: $instance;
- }
- //防止克隆对象
- private function __clone (){
- trigger_error ("not allow to clone.");
- }
- function test(){
- echo "test" ;
- }
- }
- $conn = mysql::getInstance ();
- $conn->test ();
- ?>
|