PHP Pattern Design Single Example mode

Source: Internet
Author: User

The singleton pattern is designed to prevent multiple instances of duplication, such as duplication of database connections, resulting in wasted resources.

The point is:

1/A class has only one object
2/class is self-created and cannot be declared by new
3/Purpose: This object is uniformly provided throughout the system.

Writing:

1/class defines a private static variable
Only private constructors are available in the 2/class
3/provides a static public function to create the private object itself.
4/Use __clone to prevent cloning

<?php//学习使用单例模式class Danli{    private static $db = null;    private static $num = 0;    private function __construct()    {        echo "对象已经构建完成:".self::$num."次\n";    }    public static function getInstance()    {        if(self::$db instanceof self){            echo "已经实例化,不要重复实例\n";            return self::$db;        }else{            self::$num +=1;            return  self::$db = new self();        }    }    static function test()    {        echo "调用成功\n";    }    public function __clone()    {        echo "不能克隆哦";    }}$d = Danli::getInstance();$d->test();$c = Danli::getInstance();$c->test();$d= clone $c;//

PHP Pattern Design Single Example mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.