What is PHP singleton mode?

Source: Internet
Author: User

Reply content:

In fact, a singleton pattern, plainly speaking, is that a class can only be instantiated once. But how do we make a fuss at this instantiation? In fact, there is a breakthrough is __construct () this magic method. This method means that the method is automatically executed if the class is instantiated. And if I turn this method into a protection or a private one, what would it be?

  
   
static function getInstance($class, $param = array()){    if (!isset($obj[$class])) {        $obj[$class] = new $class($param);    }    return $obj[$class];}在实例化一个类时,先判断是否有这个类的实例,如果有就不实例化,反之就实例化一个
Strong landlord is cheap,show to talk about is that you my code.

The simplest class of PHP singleton patterns:
class TestInstance{    public static $_instance = null;    //为了防止外部new这个类,所以构造方法用protected,这是单例模式的关键之处    protected function __Construct()    {        echo 'Instance,Instance,Instance..........';    }    //用一个静态变量存储类的实例,只有第一次实例化的时候才赋值,以后都直接给出静态实例    public static function getInstance()    {        if(!isset(self::$_instance)){            self::$_instance = new static();        }        return self::$_instance;    }}
  • 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.