Miguel Stevens
Miguel Stevens

Reputation: 9191

Undefined variable: _SESSION in Class

Strange Situation. I have a Projects Class which has the following constructor

public function __construct($db){
    $this->db = $db;
    $this->lang = strtolower($_SESSION['la']);
}

I'm using AJAX to call a simple get() function but the error returned is

<b>Notice</b>:  Undefined variable: _SESSION in <b>D:\Sites\proman\class\Projects.php</b> on line <b>10</b><br />

In my index.php I have session_start() so that's not the problem. I can even print_r($_SESSION) in the construct method and i see the session variable of 'la'.##

I tried adding session_start() also to the top of my Projects.php class but then I get the warning that session has already started.

This is my session init at the top of index.php ## it also set's a default language (la) variable if none is chosen by the user

<?php
    session_start();
    if(!isset($_SESSION['la'])) $_SESSION['la'] = "EN";
?>

This is the output of the print_r() in the Projects Constructor ## Array ( [la] => FR ) Any idea whay might be going wrong here? Thanks!

Upvotes: 0

Views: 3783

Answers (1)

AeJey
AeJey

Reputation: 1457

I think

<b>Notice</b>:  Undefined variable: _SESSION in <b>D:\Sites\proman\class\Projects.php</b> on line <b>10</b><br />

is the result of your ajax call. Right?

The issue is that you are missing session_start() in the file requested with ajax. I think the file is Projects.php in you class. Since you are using ajax, not include/require the session_start() on your index.php page is not sufficient. Separate session_start() is needed for the ajax page (Projects.php here).

Add a new session_start() on your ajax page(Projects.php) and let me know whether it fixed the issue.

Upvotes: 5

Related Questions