单身会话问题

时间:2011-07-20 18:25:18

标签: php oop singleton

可能是一个快速修复,但无法弄清楚我哪里出错了。我正在设置一个简单的单例Session类,但是我收到了以下错误,所以我显然没有正确设置:

我在这里犯了一个明显的错误吗?谢谢你的帮助

警告:session_start()[function.session-start]:无法发送会话缓存限制器 - 已发送的标头...

class Session { 

    // Session singleton
    protected static $instance;

    private function __construct()
    {
        //start the session
        session_start();

        Session::$instance = $this; 
    }

    public static function instance()
    {
        if (Session::$instance === NULL)
        {
            // Create a new instance
            new Session;
        }

        return Session::$instance;
    }
}

3 个答案:

答案 0 :(得分:1)

在致电session_start()之前,您无法输出任何数据。在实例化该类之前,请确保没有回声或打印或任何吐出数据的内容。

答案 1 :(得分:0)

也许这会有所帮助......

http://php.net/manual/en/function.session-start.php

For the error: 

Warning: session_start(): Cannot send session cache limiter - headers already sent ... 

this kind of errors would occur, when the encoding of your script file needs to send some headers just after your script starts to execute, 

this happens mostly with the scripts using normal utf8 encoding. 

To overcome the issue, use utf8(without BOM) encoding provided by notepad++ and most modern editors. Using utf8 encoding and cookie based sessions, will result in headers already sent by error.

答案 2 :(得分:0)

headers already sent错误的问题在于您发送了一些正文内容,html,可能是空格,...这个问题可以通过两种方式删除。

  1. Session的创建成为您脚本的第一件事 - 在任何输出操作之前通过调用Session::instance()开始。

  2. 使用输出缓冲。第一条指令应为ob_start(),最后一条ob_end_flush()