我有以下类,它有很多私有变量。
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之前的日子里,我从数据库中检索信息,将其放入变量中,然后使用compress()发送和extract()来获取所有变量。这是否会起作用,就像在我的类中的returnAttributes()方法一样?
答案 0 :(得分: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;
}