Home » Php » php – Class static variables reset when I call them in other file

php – Class static variables reset when I call them in other file

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am practicing PHP, and the issue I encountered today is my static variable getting reset every time I call it.

Login Page after verfied user from DB

<?php
Session::onlogin(1);
?>

This is my session class it has a func onlogin and I send some data to it from another file which change $is_signed to true. But the issue is variable $is_signed getting reset when I call it from index.php it returns false

<?php
class Session {

private static $is_signed = false;

function __construct(){
    session_start();
}

public static function is_signed_in(){
    return self::$is_signed;
}

public static function onLogin($userid){
    if($userid){
        session_regenerate_id();
        $_SESSION['user_id'] = $userid;
        self::$is_signed = true;
        return true;
    }
}
}
$session = new Session;
?>

Now I am calling it in index.php as below

if(Session::is_signed_in()){
    echo "logged In";
}
else {
echo "error";
?>

I don’t know where I am creating any error but when I call the methods.

How to&Answers:

So i asume this

class.php

class Session
{

    private static $is_signed = false;

    function __construct()
    {
        session_start();
    }

    public static function is_signed_in()
    {
        return self::$is_signed;
    }

    public static function onLogin($userid)
    {
        if ($userid) {
            session_regenerate_id();
            $_SESSION['user_id'] = $userid;
            self::$is_signed = true;
            return true;
        }
    }
}
$session = new Session;

login.php

<?php

require 'class.php';
$session = new Session;
Session::onlogin(1);
var_dump(Session::is_signed_in());// output true

index.php

<?php declare(strict_types = 1);
require 'class.php';

var_dump(Session::is_signed_in());// output false

think about it that login.php and index.php are 2 separate programs not aware one of each other.Thats why you try put SESSION there change

    function __construct()
    {
        session_start();
        if (isset($_SESSION['user_id'])){
            self::$is_signed = true;
        }
    }

and you are done