Home  >  Article  >  Backend Development  >  单例模式之php兑现

单例模式之php兑现

WBOY
WBOYOriginal
2016-06-13 11:14:33806browse

单例模式之php实现

单例模式保证某个类只有一个实例;

1,静态成员变量保存类的唯一实例

2,声明构造函数和克隆方法为私有,防止new一个实例

3,提供一个公共的静态方法来访问这个实例,返回唯一实例的的引用

class InstanceDemo
{

    private static $_instance;//静态成员变量保存唯一的实例


    private function __construct()//构造函数
    {
        echo 'I am Construceted';
    }

    public static function GetInstance()
    {
        if(!isset(self::$_instance))
        {
            $c=__CLASS__;
            self::$_instance=new $c;//new  self()
        }
        return self::$_instance;
    }


  //覆盖__clone()方法,禁止克隆 

    private function __clone()  
    {  
        echo "禁止clone";
    }

        function test()
    {
        echo("test  instance");

    }
}
   //调用静态的共有方法得到唯一的一个实例
    $test = InstanceDemo::GetInstance();
    $test->test();
    //禁止克隆哦
    $test_clone = clone $test;

?>
1楼wangeen昨天 09:51
php的语法是不是和java差不多
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn