duanlei0282 2018-01-23 08:10
浏览 70
已采纳

PHP单例不能在简单的类中访问

First Happy New Year to all.

I'm stuck on a simple case in php and maybe you can lightup my mind here:

I have php page with js script. This script (based on jquery) contains a document ready event function that makes an Ajax call :

$.ajax({
    type: "POST",
    url: "actions/DatasourceEmail.php",
    data: param,                   
    dataType: "json",
    dataFilter: function(data, type){ 
        return data;
    },
    error: function(xhj, statut, thrown){
        alert(xhj.responseText);
    },
    success: function(result){
    ...

This working well. My problem is on server side. When I instanciate a class, the code doesn't go inside and instanciate, by the way I don't think so. I have a logging function (singleton) which traces on the first call. But not inside the class when I instanciate

class testclass
{
    function instance(){
        ApplicationMedSoft::CurrentApplication()->Trace("@@@@ initialisation !!!");
    }
}

...

ApplicationMedSoft::CurrentApplication()->Trace("@@@@ initialisation !!!");
$flex = new testclass();

Result log:

    ...
    [23/01/2018 9:06:34] - [SQL] ==> 1 resultat(s)
    [23/01/2018 9:06:34] - @@@@ initialisation !!!  <= First call
    ??? second (inside class??)

All my files are correctly included It's like my singleton is not working is this class, but in some others classes it's working. By looking for too much the problem, I thik I can't see it anymore. Help :)

Thanks for reading

Iainh.

  • 写回答

2条回答 默认 最新

  • dongmu9253 2018-01-23 08:24
    关注

    If your expecting your class to log something when it's just created you need to call your function __construct and not instance. So you class should be something like...

    class testclass
    {
        public function __construct(){
            ApplicationMedSoft::CurrentApplication()->Trace("@@@@ initialisation !!!");
        }
    }
    

    I would also recommend that you change the class name to TestClass as this is more convention.

    If you want the class to behave like a singleton class, then you need to do something slightly different...

    class TestClass
    {
        public static function instance(){
            ApplicationMedSoft::CurrentApplication()->Trace("@@@@ initialisation !!!");
        }
    }
    

    Adding static to the method allows you to call it without creating a new object, call it using...

    $flex = TestClass::instance();
    

    Have a read of http://www.phptherightway.com/pages/Design-Patterns.html for more info.

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作