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!