0

I have this class:

class TestClass
{
    var $testvar;
    public function __construct()
    {
        $this->$testvar = "Hullo";
        echo($this->$testvar);
    }
}

And this method for accessing:

function getCurrent()
{
    $gen = new TestClass();
}

I get the following error:

Notice: Undefined variable: testvar in /Users/myuser/Sites/codebase/functions.php on line 28
Fatal error: Cannot access empty property in /Users/myuser/Sites/codebase/functions.php on line 28

What's going on?

3 Answers 3

6

You don't need to use the variable reference when you access the variable:

$this->testvar;

By using $this->$testvar, your PHP script will first look for $testvar, then find a variable in your class by that name. i.e.

$testvar = 'myvar';
$this->$testvar == $this->myvar;
Sign up to request clarification or add additional context in comments.

Comments

3

Remove the $ before testvar in your call to it:

$this->testvar = "Hullo";
echo($this->testvar); 

Comments

2

Since var is deprecated I'd suggest to declare it as one of private, public or protected.

class TestClass
{
    protected $testvar;
    public function __construct()
    {
        $this->testvar = "Hullo";
        echo $this->testvar;
    }
}

Comments

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.