PHP Singleton Pattern Code snippet

Source: Internet
Author: User

1<?PHP2 3 error_reporting(E_all|e_strict);4 5 classsingle{6 7      Public $hash;8 9     Static protected $ins=NULL;Ten  One     Final protected function__construct () {//final can be inherited and cannot be overridden (prevents subclasses from overriding the constructor method) A         $this->hash =Mt_rand(1,9999); -     } -  the     Static  Public functiongetinstance () { -         if(Self::$insInstanceof self) {//instanceof Determine if an object is an instance of a class -             returnSelf::$ins; -         } +Self::$ins=NewSelf (); -         returnSelf::$ins;  +     } A } at  - $s 1= Single::getinstance (); - $s 2= Single::getinstance (); -  - Var_dump($s 1); - Var_dump($s 2); in  - //son class inherits single class to classSonextendssingle{ + } -  the $s 1= Son::getinstance (); * $s 2= Son::getinstance (); $ Panax Notoginseng Var_dump($s 1); - Var_dump($s 2);

Page output

Object (single) [1]    Public ' hash ' = = int 9762object(Single) [1  ]public ' hash ' = int 9762object( Single) [1]  public ' hash ' = = int 9762object(Single) [1]     Public ' hash ' = int 9762

PHP Singleton Pattern Code snippet

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.