Controls the number of PHP class instantiation times! -PHP source code

Source: Internet
Author: User
Ec (2); controls the number of php class instantiation times! To ensure the effective use of server resources, and a class, such as a template or database, needs to be instantiated only once on a page! That is, only one instance is running in the memory! To avoid repeated instantiation, it is necessary to control the number of php class instantiation times! The method is actually very simple: it is to give the class an external interface, private constructor, abandon the method that can use new to instantiate the class outside the class! The following is an example. I believe that script ec (2) and script

Controls the number of php class instantiation times! To ensure the effective use of server resources, and a class, such as a template or database, needs to be instantiated only once on a page! That is, only one instance is running in the memory! To avoid repeated instantiation, it is necessary to control the number of php class instantiation times! The method is actually very simple: it is to give the class an external interface, private constructor, abandon the method that can use new to instantiate the class outside the class! The following is an example. I believe you will understand it at a glance! (PHP5 and later versions! )

Class test {
Const name = ''test '';
Public static $ havenew = false;
Public $ name = ''I am restricted to being instantiated 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;
}
}
}
$ Class1 = test: inter ();
Var_dump ($ class1 );
Echo''
'';
$ Class2 = test: inter ();
Var_dump ($ class2 );
?>

Here all instances use the inter () method in test to instantiate the object! Because the constructor itself cannot be directly accessed, it does not exist and can be instantiated using 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.