Gausie
Gausie

Reputation: 4359

Undefined variable in __construct()... but I did define it

I've written the following piece of code:

Class stackOverflowExample {

    private $hash;
    private $cookie_file;

    public function __construct(){

        @session_start();

        if(isset($_SESSION['gc_hash'])){
                $this->$hash = $_SESSION['gc_hash'];
        }else{
                $this->$hash = md5(time());
                $_SESSION['gc_hash'] = $this->$hash;
        }

        $this->$cookie_file = "./cookies/{$this->$hash}.txt";

    }

}

But I'm getting this error

Notice: Undefined variable: hash in /var/www/gausie/gc/GeoCaching.Class.php on line 21

Fatal error: Cannot access empty property in /var/www/gausie/gc/GeoCaching.Class.php on line 21

In the original code, line 21 refers to $this->$hash = $_SESSION['gc_hash'];.

I can't see why this is happening, although I'm new to OO PHP. Any ideas?

Upvotes: 1

Views: 1602

Answers (1)

RiaD
RiaD

Reputation: 47640

just replace $this->$hash by $this->hash

$this->$hash means variable with name equals to variable $hash value

Upvotes: 10

Related Questions