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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)