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 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?