PHP object-oriented: Design Mode-singleton Mode)

Source: Internet
Author: User

Http://www.yzswyl.cn/blread-1601.html

Today, a friend in the group asked "private function _ construct () {}" to prevent direct new objects? So I also went to the Internet to find a detailed document for analysis. I feel that it is quite good. I recommend it to you:

The problem to be solved in singleton mode is "How to make this class have only one instance ".

Database connections are widely used in our web applications. If we establish connections with databases repeatedly, more system resources will be consumed.

To solve this problem, it is necessary to establish a unique database connection.

How do we know whether the connection to this database has been established? Or do I need to create it now?

The Singleton mode can solve this problem.

Let's assume that we need a class to complete the function with only one copy in the memory. What should we do?

We use the previous knowledge to write a singleton example step by step.

As mentioned above, you can create an object every time you use the new class name. We must disable External programs from using the new class name to create multiple instances.

Solution: Set the constructor to private so that the constructor can only be called internally, but not externally. In this way, this class cannot be used externally to create multiple instances using the new method.

The following are classes that cannot be instantiated externally using new.

?
<?class A{    private function __construct(){}    }$a = new A();?>

The program running result is:

?
Fatal error: Call to private A::__construct() from invalid context in E:\PHPProjects\test.php on line 6

We have disabled the external use of new to instantiate this class. How can we make users access this class? The front door is blocked. We need to leave a backdoor for the user.
The solution is: static modification. You can directly access this method without instantiating a class.

?
// The new class cannot be instantiated. <br>// Leave the static method to external access. <br>// Return the instance within the method. <br><?class A{    private function __construct(){}    static function getClassA(){        $a = new A();        return $a;    }        }// The instance of A is indeed returned here, but it is not the same object.$a1 = A::getClassA();$a2 = A::getClassA();echo "\ $ A1 Class is".get_class($a1).", \ $ A2 is".get_class($a1);if($a1 === $a2){    echo "<Br> \ $ a1 \ $ a2 points to the same object .";}else{    echo "<Br> \ $ a1 \ $ a2 is not an object .";}?>

The program running result is:

?
$a1 The class is,$a2 Yes$a1 $a2 Not an object.

We have returned an instance of A through the static method. But there are still problems. How can we ensure that we obtain the same instance through multiple operations?

Solution: there is only one static attribute internally. Static
Property can be effectively called by static methods. Set this attribute to private to prevent external calls. Set this attribute to null first. Determine whether this attribute is
Null. If it is null, a new instance of this class will be created and assigned to this static property. If it is not null, the static attribute pointing to the instance is returned.

?
// The new class cannot be instantiated. <br>// Leave the static method to external access. <br>// Return the instance within the method. <br>// Define static attributes to ensure that the instance can be called by static methods. <br>// Add the judgment part. <br><?class A{    private static $a = null;    private function __construct(){}    static function getClassA(){        if( null == self::$a){            self::$a = new A();        }               return self::$a;    }        }// The instance of A is indeed returned here, but it is not the same object.$a1 = A::getClassA();$a2 = A::getClassA();echo "\ $ A1 Class is".get_class($a1).", \ $ A2 is".get_class($a1);if($a1 === $a2){    echo "<Br> \ $ a1 \ $ a2 points to the same object .";}else{    echo "<Br> \ $ a1 \ $ a2 is not an object .";}?>

The program running result is:

?
$a1 The class is,$a2 Yes$a1 $a2 Point to the same object.

At this point, we have written a simple Singleton mode.

Now, you can try to write a database connection class in the application Singleton design mode.

Remember the effect and Writing Method of Singleton mode.

Http://www.yzswyl.cn/blread-1601.html

Today, a friend in the group asked "private function _ construct () {}" to prevent direct new objects? So I also went to the Internet to find a detailed document for analysis. I feel that it is quite good. I recommend it to you:

The problem to be solved in singleton mode is "How to make this class have only one instance ".

Database connections are widely used in our web applications. If we establish connections with databases repeatedly, more system resources will be consumed.

To solve this problem, it is necessary to establish a unique database connection.

How do we know whether the connection to this database has been established? Or do I need to create it now?

The Singleton mode can solve this problem.

Let's assume that we need a class to complete the function with only one copy in the memory. What should we do?

We use the previous knowledge to write a singleton example step by step.

As mentioned above, you can create an object every time you use the new class name. We must disable External programs from using the new class name to create multiple instances.

Solution: Set the constructor to private so that the constructor can only be called internally, but not externally. In this way, this class cannot be used externally to create multiple instances using the new method.

The following are classes that cannot be instantiated externally using new.

?
<?class A{    private function __construct(){}    }$a = new A();?>

The program running result is:

?
Fatal error: Call to private A::__construct() from invalid context in E:\PHPProjects\test.php on line 6

We have disabled the external use of new to instantiate this class. How can we make users access this class? The front door is blocked. We need to leave a backdoor for the user.
The solution is: static modification. You can directly access this method without instantiating a class.

?
// The new class cannot be instantiated. <br>// Leave the static method to external access. <br>// Return the instance within the method. <br><?class A{    private function __construct(){}    static function getClassA(){        $a = new A();        return $a;    }        }// The instance of A is indeed returned here, but it is not the same object.$a1 = A::getClassA();$a2 = A::getClassA();echo "\ $ A1 Class is".get_class($a1).", \ $ A2 is".get_class($a1);if($a1 === $a2){    echo "<Br> \ $ a1 \ $ a2 points to the same object .";}else{    echo "<Br> \ $ a1 \ $ a2 is not an object .";}?>

The program running result is:

?
$a1 The class is,$a2 Yes$a1 $a2 Not an object.

We have returned an instance of A through the static method. But there are still problems. How can we ensure that we obtain the same instance through multiple operations?

Solution: there is only one static attribute internally. Static
Property can be effectively called by static methods. Set this attribute to private to prevent external calls. Set this attribute to null first. Determine whether this attribute is
Null. If it is null, a new instance of this class will be created and assigned to this static property. If it is not null, the static attribute pointing to the instance is returned.

?
// The new class cannot be instantiated. <br>// Leave the static method to external access. <br>// Return the instance within the method. <br>// Define static attributes to ensure that the instance can be called by static methods. <br>// Add the judgment part. <br><?class A{    private static $a = null;    private function __construct(){}    static function getClassA(){        if( null == self::$a){            self::$a = new A();        }               return self::$a;    }        }// The instance of A is indeed returned here, but it is not the same object.$a1 = A::getClassA();$a2 = A::getClassA();echo "\ $ A1 Class is".get_class($a1).", \ $ A2 is".get_class($a1);if($a1 === $a2){    echo "<Br> \ $ a1 \ $ a2 points to the same object .";}else{    echo "<Br> \ $ a1 \ $ a2 is not an object .";}?>

The program running result is:

?
$a1 The class is,$a2 Yes$a1 $a2 Point to the same object.

At this point, we have written a simple Singleton mode.

Now, you can try to write a database connection class in the application Singleton design mode.

Remember the effect and Writing Method of Singleton 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.