苗火 Nicholas
[php]PHP下的单例模式实例
2015-11-11 萧
下面是一个单例模式的例子,同时满足以下要求:



①类只能有一个实例(不能多)

②类必须能够自行创建这个实例

③必须自行向整个系统提供这个实例,换句话说:多个对象共享一块内存区域,比如,对象A设置了某些属性值,则对象B,C也可以访问这些属性值





<?php

    class SqlHelper{

        private static $_instance;

        public $_dbname;

        private function __construct(){

            

        }

        //getInstance()方法必须设置为公有的,必须调用此方法

        public static function getInstance(){

            //对象方法不能访问普通的对象属性,所以$_instance需要设为静态的

            if (self::$_instance===null) {

                //self::$_instance=new SqlHelper();//方式一    

                self::$_instance=new self();//方式二        

            }

            return self::$_instance;

        }

        public function getDbName(){

            echo $this->_dbname;

        }

        public function setDbName($dbname){

            $this->_dbname=$dbname;

        }

    }

//    $sqlHelper=new SqlHelper();//打印:Fatal error: Call to private SqlHelper::__construct() from invalid context 

    $A=SqlHelper::getInstance();

    $A->setDbName('数据库名');

    $A->getDbName();

//    unset($A);//移除引用

    $B=SqlHelper::getInstance();

    $B->getDbName();

    $C=SqlHelper::getInstance();

    $C->getDbName();

    

?>


发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容