search
Homephp教程php手册单例模式之php实现

单例模式之php实现

Jun 13, 2016 am 10:54 AM
phpkeepensureSingletonvariableonlystatementExampleaccomplishmembermodelofkindstatic

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

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;

 

?>

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function