duanlaofu4108 2010-02-18 00:58
浏览 72
已采纳

PHP Singleton:没有持有实例

I'm just becoming dive into php after ages working in vb.net.

I wanna write a logger class that runs as singleon over my webapp, here the code:

class cLog{

private $data = NULL;


static private $instance = NULL;

static public function getInstance(){
    if(self::$instance == NULL){
        echo "empty!";
        self::$instance = new cLog();           
    }   
    return self::$instance;
}


private function __construct(){     
}   
private function __clone(){     
}



public function getData(){
    return self::getInstance()->data;
}

public function trace($o){
    self::getInstance()->data[] = $o;
}

}

What I expect is that, as i switch between pages of my application that make several calls to the cLog::trace() method, the data array increases and it's filled with all traces. But what I get is: everytime i run a page, the $instance is null so the object restarts (as you can see, I put an echo "empty!" line in the instance getter: it shows everytime)

I guess there's something I'm misunderstanding in the php application-lifecycle....

Here there's an usage example:

cLog::getInstance()->trace("hello world");
$logs = cLog::getInstance()->getData();

Thanks

  • 写回答

4条回答 默认 最新

  • dongqie4233 2010-02-18 01:17
    关注

    PHP uses a "share nothing" architecture. This means (among other things) that nothing is shared between page loads. Unlike .NET, where the application is started on the first page hit and runs until stopped, just servicing requests as they come. In PHP, every time a page is requested the application is essentially compiled and run from scratch.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?