dongshi3818 2014-08-24 06:21
浏览 17
已采纳

基于会话的消息不在类中工作

I have a main file (framework.php) that requires a few classes. For simplicity of my question lets assume only messages with the class Messages and automate with the class Automate. The messages class stores session messages that appear to the user on the frontend whenever they refresh their page .etc. When I add a message in Automate I do so via $msg = new Messages; $msg->add('s', 'Hello World!'); However I keep repeating $msg = new Messages everytime I want to add a $msg, and because this is messy, I want to just call the class once. So I initialize the class in the constructor like so:

class Automate
{
    protected $msg;
    //public $connection;
    public $cke;
    public $debug = false;
    public $disallow_insert;
    public $bImgUp = BACKEND_IMAGE_UPLOAD_PATH;
    public $fImgUp = FRONTEND_IMAGE_UPLOAD_PATH;
    public function __construct() {
        global $disallow_insert;
        $this->disallow_insert = $disallow_insert;
        $this->cke = (bool) self::ckeCheck();
        $this->msg = new Messages();

    }

and in my main file I add it $msg = new Messages(); so I can just call the display function echo $msg->display();

However this method does not work (no errors, but still), the only thing that seems to work is when I initialize the $msg = new Messages(); before every add or display. What am I doing wrong?

I should mention I'm using this session based message script.

UPDATE: I have determined the the messages are getting added by commenting out the clear function in the messages class. It almost seems as though the variable is getting unset before displaying.

  • 写回答

1条回答 默认 最新

  • douchuitang0642 2014-08-25 00:09
    关注

    I figured it out after researching OOP practices. I made the messages class a singelton via:

    public static function getInstance()
    {
        static $instance = NULL;
        if (NULL === $instance) {
            $instance = new static();
        }
    
        return $instance;
    }
    

    and in my classes

    var $msg;
    public function __construct() {
        $this->msg = Messages::getInstance();
    }
    

    I figure the messages class needed to be constructed once, not multiple times which is why the function clear kept being called!

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

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题