1

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?

1 Answer 1

10

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

RiaD's point being that you only require the $ before the this and nowhere else when using PHP's object notation.
Correct :) - $this->$hash would reference a variable named like the content of $hash that is placed inside the class. So for it to work you would need to declare $hash = 'hash'; once done that it would work like that too, but that's not really the correct way of doing it. See the answer for how to do that :)
Ah. I feel silly. Upvotes. EDIT: I realise this isn't Reddit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.