Mac Os
Mac Os

Reputation: 97

Global variable is NULL in class method

My first line in my script I have:

$db = new db_class();

This is just an example to start the db object. Then I have:

class main {

    function init() {
        $this->session_start();
    }

    protected function session_start() {
        $sh = new session_handler();
        session_set_save_handler(
            array (& $sh, 'open'),
            array (& $sh, 'close'),
            array (& $sh, 'read'),
            array (& $sh, 'write'),
            array (& $sh, 'destroy'),
            array (& $sh, 'gc')
        );        
    }

}

All of the problems are in the in session_handler class. This code:

public function write($id, $data) {
    global $db;  

    var_dump($db); //returns NULL
}

says that $db is NULL instead of an instance of db_class.

Note, db_class objects work except when calling the write() method:

class main {

    function init() {
        global $db;

        var_dump($db); //returns the db object correctly

        $this->session_start();
    }

    protected function session_start() {
        $sh = new session_handler();
        session_set_save_handler(
            array (& $sh, 'open'),
            array (& $sh, 'close'),
            array (& $sh, 'read'),
            array (& $sh, 'write'),
            array (& $sh, 'destroy'),
            array (& $sh, 'gc')
        );  
    }

}

Upvotes: 0

Views: 303

Answers (1)

Jaspreet Chahal
Jaspreet Chahal

Reputation: 2750

I guess the problem is at first line
$db = new $db_class();

if guess it should be like

$db = new db_class();

Or make sure that $db_class has value of class name that you wish to initialize

How about trying something like this

class main{
protected $_db;

function init($db){
    $this->_db = $db;
    $this->session_start();
}

protected function session_start() {
    $sh = new session_handler();
    session_set_save_handler(
        array (& $sh, 'open'),
        array (& $sh, 'close'),
        array (& $sh, 'read'),
        array (& $sh, 'write'),
        array (& $sh, 'destroy'),
        array (& $sh, 'gc')
    );        
}
public function write($id, $data) {
    vardump($this->_db);
}
}

Upvotes: 1

Related Questions