2015-12-12 37 views
0

如何從構造函數獲取並處理變量?訪問Codeigniter中的構造函數變量

當我初始化我的功能你好我得到錯誤:

Message: Undefined variable: type2

庫:

class MyLibrary { 


public function __construct($params) 
{ 
    echo $params['type']; 

    //I WANT TO DISPLAY TYPE2 BY HELLO FUNCTION 
    $type2 = 'asdasdasd'; 
} 

public function hello(){ 

    return $type2; 
} 
} 

我的控制器:

public function test() 
{ 
    $params = array('type' => 'large', 'color' => 'red'); 
    $this->load->library('TwitterAPI', $params); 

    //I WANT TO DISPLAY $TYPE2 
    echo $this->twitterapi->hello(); 

} 
+1

$ this-> type2應該用繼承的方法來做,所以** public function hello(){return $ this-> type2; } ** – ggdx

+0

@DanWhite我得到錯誤:'未定義的屬性:MyLibrary:$ type2' –

+0

在構造函數中註釋/刪除echo ...。此外,你是否啓動了圖書館? $ this-> load-> library('mylibrary') – ggdx

回答

2

創建一個私有成員變量:

class MyLibrary { 

    private $type2; 

    public function __construct($params) 
    { 
     echo $params['type']; 

     //I WANT TO DISPLAY TYPE2 BY HELLO FUNCTION 
     $this->type2 = 'asdasdasd'; 
    } 

    public function hello() 
    { 

     return $this->type2; 
    } 

}