简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM