0

多くのプライベート変数を持つ次のクラスがあります。

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() メソッドのように機能しますか?

4

1 に答える 1

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;
}
于 2012-02-07T17:16:35.820 に答える