I have the following class, which has a lot of private variables.

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

}
}

I want to return all of the attributes as variables with their values, so that I can pre-fill a form field. I have a database query which fills all of the attributes (which works as proven by testing). In my pre-OO days, I retrieved the info from the db, put it into variables, then used compress() to send and extract() to get all the variables. Is this something that will work, as in the returnAttributes() method in my class?

有帮助吗?

解决方案

Why make it so complicated? Here's an example with a lot less code which has the desired behaviour.

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

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

    return $list;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top