Home > php教程 > php手册 > 单例模式之php实现

单例模式之php实现

WBOY
Release: 2016-06-13 10:54:37
Original
1288 people have browsed it

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

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;

 

?>

source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template