2009-11-02 50 views
0

我有這個類:PHP類變量問題

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

而且這種方法訪問:

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

我收到以下錯誤:

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

這是怎麼回事?

回答

3

在呼叫的testvar之前取出$它:

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

謝謝。我錯過了。 – 2009-11-02 21:12:26

6

你不需要在訪問變量使用變量引用:

$this->testvar; 

使用$this->$testvar,你PHP腳本將首先查找$testvar,然後通過該名稱查找類中的變量。即

$testvar = 'myvar'; 
$this->$testvar == $this->myvar; 
+0

+1爲詳細說明錯誤發生的原因 – 2009-11-02 21:15:51

2

由於VAR不贊成我建議將其聲明爲私有,公共或受保護的。

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