- 论坛徽章:
- 0
|
请看下面的代码:- <?php
- class Singleton{
- private static $instance;
- private function __construct(){
- self::$instance = &$this;
- echo '<br/>','====0','<br/>';
- if(self::$instance == null)
- echo '<br/>','====1','<br/>';
- else
- echo '<br/>','====2','<br/>';
- }
- public static function getInstance(){
- if(self::$instance == null){
- self::$instance = new Singleton();
- echo '<br/>','====3','<br/>';
- }else
- echo '<br/>','====4','<br/>';
- return self::$instance;
- }
- }
- $instance1 = Singleton::getInstance();
- ?>
复制代码 输出结果:
====0
====2
====3
请问为什么构造函数输出self: instance不为空,而getInstance()输出self: instance为空呢?
这种单例类还不能new对象,构造方法是怎么执行的呢?
百思不得其解,请高手帮忙解答,谢谢。 |
|