2011-03-15 40 views
1

嗯,這是如何做到的?幫助訪問我的班級裏面的變量

我有一個類

class Themes extends Access 
{ 
    public $theme_name; 
    public $theme_by; 
    public $theme_by_email; 
    public $theme_by_website; 
    public $theme_description; 
    public $theme_thumb; 
    public $theme_source; 
    public $theme_uploaded_on; 

    public function __construct() 
    { 
     parent::__construct(); 
     //$this->get_theme(); 
    } 

    public function get_theme() 
    { 
     $sql = "SELECT * 
       FROM `user_themes` 
       WHERE `user_id` = " . $this->session->get('user_id'); 
     if($this->db->row_count($sql)) 
     { 
      $result   = $this->db->fetch_row_assoc($sql); 
      $this->$theme_name  = $result['theme_name']; 
      $theme_by   = $result['theme_by']; 
      $theme_by_email = $result['theme_by_email']; 
      $theme_by_website = $result['theme_by_website']; 
      $theme_description = $result['theme_description']; 
      $theme_source  = $result['theme_source']; 
      $theme_uploaded_on = $result['theme_uploaded_on']; 
     }else{ 
      die('no results'); 
     } 
    } 
} 

我如何可以訪問類之外的這些變量和它們的內容是什麼?

在我的PHP頁面

$theme = new Themes(); 

我嘗試使用

$theme->them_name訪問我的變量,但我得到一個未定義的錯誤

,但真的不知道我怎麼可以訪問可變...

回答

3

根據您當前的設置中,所有你需要做的就是調用:

$theme->theme_name; 
$theme->theme_by; 
etc 

然而,它通常是不好的做法,使實例變量公開,而是將它們設爲私人的並使mutator methods

一個例子是:

private $theme_name; 

public function getThemeName(){ 
    return $this->theme_name; 
} 

public function setThemeName($theme){ 
    $this->theme_name = $theme; 
} 
+0

我想過,但我不想將不得不作出7個調用數據庫只是爲了得到我需要 – Eli 2011-03-15 02:59:34

+0

您不必到信息。您可以調用$ theme-> get_theme(),這將是您唯一的數據庫調用。之後,使用mutator方法。使用setThemeName之類的一些附加好處,您可以在設置該值之前添加可選驗證。 – 2011-03-15 03:05:21

+0

嗯,有點困惑,從哪裏調用$主題?例如, – Eli 2011-03-15 03:31:02

1
$this->theme_name  = $result['theme_name']; 
$this->theme_by   = $result['theme_by']; 

關於的注意事項3210前置。

之後,你可以使用$theme->theme_name訪問數據等