Reputation: 28883
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?
Upvotes: 0
Views: 247
Reputation: 12433
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;
}
}
Upvotes: 2
Reputation: 27573
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;
Upvotes: 6
Reputation: 9196
Remove the $ before testvar in your call to it:
$this->testvar = "Hullo";
echo($this->testvar);
Upvotes: 3