OO PHP 将所有私有变量作为页面上的变量返回

OO PHP returning all private variables as variables on page

提问人:Phil Young 提问时间:2/8/2012 更新时间:2/8/2012 访问量:510

问:

我有以下类,它有很多私有变量。

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() 方法一样?

PHP 数组 OOP 变量

评论


答:

4赞 Dan 2/8/2012 #1

为什么要让它变得如此复杂?下面是一个示例,其中的代码要少得多,但具有所需的行为。

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赞 Phil Young 2/8/2012
谢谢,这对眼睛来说要容易得多!