2012-02-07 154 views
0

我有以下類,它有很多私有變量。OO PHP將所有私有變量作爲變量返回

class plantOfTheMonth { 

//Declare which centre(s) are being used 
private $centre = ""; 

//Declare the attributes of the current Plant Of The Month 
private $name = ""; 
private $latinName = ""; 
private $image = ""; 
private $imageAlt = ""; 
private $imageLink = ""; 
private $strapLine = ""; 
private $description = ""; 
private $colour = ""; 
private $centres = ""; 

//Declare variables for error handling 
private $issue = ""; 
private $issueCode = ""; 

public function __construct() { 

} 

public function returnAttributes() { 

    $list = ""; //Set an Empty List 

    foreach($this as $key => $value) { 

     decodeText($value); //decode performs a stripslashes() 
     $$key = $value; //Use a variable variable and assign a value to it 
     $list .= "'".$key."', "; //add it to the list for the compress() 

    } 

    $list .= substr($list, 0, -2); //Take the final ", " off 
    return compact($list); //return the list of variables as an array 

} 
} 

我想回到所有的屬性與他們的價值觀變量,這樣我就可以預先填充表單字段。我有一個數據庫查詢,它填充了所有的屬性(工作如同測試所證明的那樣)。在OO之前的日子裏,我從db中獲取信息,將它放入變量中,然後使用compress()來發送和提取()以獲取所有變量。這是否會起作用,正如我的類中的returnAttributes()方法?

回答

4

爲什麼這麼複雜?這是一個很少代碼的例子,它具有所需的行爲。

public function returnAttributes() 
{ 
    $list = array(); //Set an Empty List 

    foreach(array_keys(get_class_vars(__CLASS__)) as $key) 
    { 
     $list[$key] = $this->$key; 
    } 

    return $list; 
} 
+0

謝謝,這對眼睛來說更容易! – 2012-02-08 15:19:22

+0

不客氣。 – Dan 2012-02-08 15:21:16