2013-05-31 128 views
0

我嘗試使用函數創建基本類。一旦創建了該類的一個實例new BaseClass("hello"),那麼構造函數會將該參數保存到一個變量中。 ->ret_text()應該返回這個變量,但它不起作用。錯誤是:unexpected T_OBJECT_OPERATOR在類中使用構造函數和公共函數

class BaseClass { 
    var $txt; 

    function __construct($text) { 
     $txt = $text; 
    } 

    public function ret_text() { 
     return $txt; 
    } 
} 

echo (new BaseClass("hello"))->ret_text(); 

回答

4

你應該$this->variableName訪問類變量,其中$this是指你在類

在您的例子$txt不是爲類變量$txt但只有一個變量。目前的功能(__construct(),ret_text()或其他)。您也不能在課程初始化後直接調用方法,即(new Class())->methodName();將不適用於PHP version < 5.4。但是,它將適用於PHP version => 5.4

相反試試這個:

class BaseClass { 
    var $txt; 

    function __construct($text) { 
     $txt = 'This is a variable only for this method and it\'s not $this->txt.'; 
     $this->txt = $text; 
    } 

    public function ret_text() { 
     $txt = 'This is a variable only for this method and it\'s not $this->txt.'; 
     return $this->txt; 
    } 
} 

$bc = new BaseClass("hello"); 
echo $bc->ret_text(); 
相關問題