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 SPSS分类模型实训题步骤
  • ¥15 求解决扩散模型代码问题
  • ¥15 工创大赛太阳能电动车项目零基础要学什么
  • ¥20 limma多组间分析最终p值只有一个
  • ¥15 nopCommerce开发问题
  • ¥15 torch.multiprocessing.spawn.ProcessExitedException: process 1 terminated with signal SIGKILL
  • ¥15 QuartusⅡ15.0编译项目后,output_files中的.jdi、.sld、.sof不更新怎么解决
  • ¥15 pycharm输出和导师的一样,但是标红
  • ¥15 想问问富文本拿到的html怎么转成docx的
  • ¥15 我看了您的文章,遇到了个问题。