Several ways to implement a single piece pattern in PHP

Source: Internet
Author: User

Single-piece mode is a design pattern that we often use in development, using PHP5 object-oriented features, we can easily build the application of single piece mode, the following is a single piece mode in PHP several implementation methods:

class Stat{
    static $instance = NULL;

    static function getInstance(){
        if(self::$instance == NULL){
            self::$instance = new Stat();
        }

        return self::$instance;
    }

    private function __construct(){
    }

    private function __clone(){
    }

    function sayHi(){
        return "The Class is saying hi to u ";
    }
}

echo Stat::getInstance()->sayHi();

This is the most common way to return a unique class instance in a GetInstance method.

With a little modification of the example here, you can produce a generic method, just call any class that you want to use in a single piece.

class Teacher{
    function sayHi(){
        return "The teacher smiling and said 'Hello '";
    }

    static function getInstance(){
        static $instance;

        if(!isset($instance)){
            $c = __CLASS__;
            $instance = new $c;
        }

        return $instance;
    }
}

echo Teacher::getInstance()->sayHi();

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.