2012-02-07 157 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