这个东西虽然早就看过,但经常不用又忘了。哎,很多东西需要不断的实践操作。。。。。。。。。。。。。
其实原理就是构造函数这里做判断,不让直接实例化。需要用静态STATIC变量作记录。私有化private
这是我自己随便写的:
- class MyClass{
- private static _instance;
- private myClass(){}
- public getInstance(){
- if(_instance == null){
- news myClass(); //实例化自身类,private在自己内中实例化
- }
- return _instance;
- }
- }
网摘一:
02 | static function getInstance() |
04 | if (self:: $instance == NULL) { // If instance is not created yet, will create it. |
05 | self:: $instance = new User(); |
07 | return self:: $instance ; |
09 | private function __construct() |
10 | // Constructor method as private so by mistake developer not crate |
11 | // second object of the User class with the use of new operator |
14 | private function __clone() |
15 | // Clone method as private so by mistake developer not crate |
16 | //second object of the User class with the use of clone. |
24 | static private $instance = NULL; |
26 | User::getInstance()->Log( "Welcome User" ); |
网摘二:
02 | static function getInstance() |
04 | if (self:: $instance == NULL) { // If instance is not created yet, will create it. |
05 | self:: $instance = new User(); |
07 | return self:: $instance ; |
09 | private function __construct() |
10 | // Constructor method as private so by mistake developer not crate |
11 | // second object of the User class with the use of new operator |
14 | private function __clone() |
15 | // Clone method as private so by mistake developer not crate |
16 | //second object of the User class with the use of clone. |
24 | static private $instance = NULL; |
26 | User::getInstance()->Log( "Welcome User" ); |