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

감사합니다. –

+0

반갑습니다. – Dan

관련 문제