2011-09-01 35 views
1

如何讀取__construct()內的變量?__construct()內的回聲

這裏的示例代碼:

class Sample { 
    private $test; 

    public function __construct(){ 
     $this->test = "Some text here."; 
    } 
} 

$sample = new Sample(); 
echo $sample->test; 

什麼是錯的代碼?因爲__construct是自動的,我只是認爲它會在類樣本上運行並自動讀取它。

是否可以在不觸碰__construct()的情況下將其回顯出來? 謝謝。

+1

我強烈建議您閱讀http://www.php.net/manual/en/language.oop5.php –

回答

7

您需要製作$testpublic。當它是私人的時候,它只能在課堂上閱讀。

class Sample { 
    public $test; 

    public function __construct(){ 
     $this->test = "Some text here."; 
    } 
} 

$sample = new Sample(); 
echo $sample->test;