验证会话是否通过内部类引用启动


Validate if session is started through the internal class reference?

我正在创建一个PHP类,它将与$_SESSION Super global一起使用,但需要进一步考虑工作环境。我决定在调用类时不使用__construct来启动会话,而是将其留给:$Class->init();

我希望该类能够迁移到已经调用session_start的网页。。。再次回到将session_start()排除在构造函数之外。我的代码如下:

class Session { 
        protected $Session_Started = false; 
    public function init(){
        if ($this->Session_Started === false){
            session_start();
            $this->Session_Started = true;
            return true;
        }
        return false;
    }
    public function Status_Session(){
        $Return_Switch = false; 
        if (session_status() === 1){
            $Return_Switch = "Session Disabled";
        }elseif (session_status() === 2){
            $Return_Switch = "Session Enabled, but no sessions exist";
        }elseif (session_status() === 3){
            $Return_Switch = "Session Enabled, and Sessions exist";
        }
        return $Return_Switch;
    }
   /*Only shown necessary code, the entire class contents is irrelevant to the question topic */

显示代码。。很明显,我正在验证会话以前是否被两种方法调用过,内部引用:$this->Session_Started,它等于truefalse

我也在调用session_status()并验证响应。

早些时候,我说过我希望它迁移到可能已经调用session_start()的站点,如果会话已经调用,验证的最佳方法是什么?。。我想让这个类做的最后一件事是,在导入和初始化类时开始抛出错误

您需要将其与"会话已启动"检查结合起来。

public function init()
{
    if ($this->Session_Started) {
        return true;
    }
    if (session_status() === PHP_SESSION_ACTIVE) {
        $this->Session_Started = true;
        return true;
    }
    if ($this->Session_Started === false) {
        session_start();
        $this->Session_Started = true;
        return true;
    }
    return false;
}

或者在构造函数中:

public function __construct()
{
    if (session_status() === PHP_SESSION_ACTIVE) {
        $this->Session_Started = true;
    }
}