doz15449 2016-12-27 13:31
浏览 95
已采纳

Singleton模式在程序的整个生命周期中如何保留在内存中?

I have the following code:

//init X (DB initialization with credentials)
$x = MySqlConnector::getMySql();

//I destroy $x
unset($x);
$x = null;

//I try to re-initialize the database, but it is already initialized
//as evident from my logs
$x = MySqlConnector::getMySql();

Relevant function:

public static function getMySql()
{
    if (null === static::$instance)
    {
        include 'include/config.php';
        static::$instance = new MySql(DBHOST, DBUSER, DBPASS);
    }

    return static::$instance;
}

That tells me that even after I kill off the variable that was holding the initialized object, somehow MySqlConnector stayed in memory.

How? I don't think it works with any other non-static class.

  • 写回答

1条回答 默认 最新

  • dougongyou7364 2016-12-27 13:38
    关注

    Static properties exist in the global scope, and are not associated to any particular instance.

    You may be unsetting $x, but MySqlConnector::$instance stays defined.

    Typically, in this kind of scenario, $instance will be a private static, so you wont be able to access the property directly, only through accesor methods, hence guaranteeing that only the Singleton class will have access to modify the property, and you wont be changing/setting/unsetting it but through properly defined methods, if they exist.

    More info in the manual.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥40 selenium访问信用中国
  • ¥15 电视大赛投票系统的c语言代码怎么做
  • ¥20 在搭建fabric网络过程中遇到“无法使用新的生命周期”的报错
  • ¥15 Python中关于代码运行报错的问题
  • ¥500 python 的API,有酬谢
  • ¥15 软件冲突问题,软件残留问题
  • ¥30 有没有人会写hLDA,有偿求写,我有一个文档,想通过hLDA得出这个文档的层次主题,有偿有偿!
  • ¥50 有没有人会写hLDA,有偿求写,我有一个文档,想通过hLDA得出这个文档的层次主题,有偿有偿!
  • ¥15 alpha101因子里哪些适合crypto?
  • ¥15 ctrl win alt 键一直触发
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部