views:

82

answers:

3

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  A: 

Remove the $ before testvar in your call to it:

$this->testvar = "Hullo";
echo($this->testvar);
Kevin Peno
Thanks. I missed that.
Josh K
+3  A: 

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;
jheddings
+1 for the detailed description on why the error occured
Kevin Peno
+1  A: 

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;
    }
}
Alex