Control the number of instances of the PHP class!

Source: Internet
Author: User

Control the number of instances of the PHP Class! In order to ensure the efficient use of server resources, and a class, such as templates Ah, database what, in a page only need to instantiate once! That is, running only one instance in memory! To avoid repeated instantiation, then control the number of instances of the PHP class, is very necessary! The method is actually very simple: to give class an external interface, privatize (private) constructor, discard the method that can instantiate the class outside of the class using new! The following is the example I gave, I believe you will see it! (PHP5 above version!)

<?php
Class test{
Const NAME = ' Test ';
public static $havenew = false;
Public $name = ' I am limited to instantiating only once! ';
Private Function __construct () {

}
function __destruct () {
Self:: $havenew = false;
}
Public function Inter () {
if (self:: $havenew) {
echo ' class '. Self::name. ' has been instantiated! ';
return NULL;
}else{
Self:: $havenew = true;
return new self;
}
}
}
$class 1 = test::inter ();
Var_dump ($class 1);
echo ' <br/> ';
$class 2 = Test::inter ();
Var_dump ($class 2);
?>

Here are examples of objects that are instantiated through the Inter () method in test! Because the construct itself cannot be accessed directly, there is no way to instantiate it with new!

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.