oasma oasma - 2 months ago 7
PHP Question

variable won't change in PHP class

I call this method in index.php then redirect to another page...
the problem is that the variable $logged_in won't get assigned to the new value...so when I use it in the other page it acts like a false
NOTE: The session 'id', and the session 'type' do get assigned to their values.
can anyone help with this?????

class Session {
public $logged_in = false;
public function login($data) {
if ($data) {
$_SESSION['id'] = $data['id'];
$_SESSION['type'] = $data['type'];
$this->logged_in = true;
}
}
}

Answer

This is a class and therefore is lost (its properties are lost) at the end of the first scripts execution and then recreated in the second in its initial state.

Classes do not live across executions of the same script or any other script.

If you wish to maintain the objects state, you will have to save the state to a file or maybe the real SESSION so you can re-hydrate the data when the second script starts

session_start();

class Session {    

    public function login($data) {
        if ($data) {
            $_SESSION['id'] = $data['id'];
            $_SESSION['type'] = $data['type'];
            $_SESSION['logged_in'] = true;            
        }
    }

    // getter function
    public function is_logged_in()
    {
        // just in case check
        if ( isset($_SESSION['logged_in']) ) {
            return $_SESSION['logged_in'] == true;
        } else {
            return false;
        }
    }
}

Called like this

$s = new Session();
if ( ! $s->is_logged_in() ) {
    header('Location: index.php');
    exit;
}

To keep it away from the SESSION completely you could

class Session {
    public $id;
    public $type;
    public $logged_in;


    public function __construct()
    {
        if ( file_exists('my_session.txt')) {
            $obj = json_decode(file_get_contents('my_session.txt'));
            foreach($obj as $prop => $val) {
                $this->{$prop} = $val;
            }
        }
    }

    public function __destruct()
    {
        file_put_contents('my_session.txt', json_encode($this));
    }

    public function login($data) {
        if ($data) {
            $this->id           = $data['id'];
            $this->type         = $data['type'];
            $this->logged_in    = true;
        }
    }
}


$obj = new Session();
$obj->login(array('id'=>99, 'type'=>'TEST'));

print_r($obj);

$obj = null;

echo 'object nulled' . PHP_EOL;
print_r($obj);
echo ' NOTHING should be printed' . PHP_EOL;

echo 'object rehydrated' . PHP_EOL;
$obj = new Session();
print_r($obj);
Comments