2008-09-19 5 views
6

PHP에 자동 생성 클래스 변수가있는 방법이 있습니까? 나는 라고 생각한다. 나는 이것과 비슷한 것을 보았다. 그러나 나는 확실하지 않다.동적 클래스 변수

public class TestClass { 
    private $data = array(); 

    public function TestClass() { 
     $this->data['firstValue'] = "cheese"; 
    } 
} 

$this->data 배열은 항상 연관 배열입니다하지만 키는 클래스에 클래스에서 변경합니다. 링크를 정의하지 않고 $this->firstValue에서 에 액세스 할 수있는 유용한 방법이 있습니까?

그렇다면 어떤 단점이 있습니까?

$this->data 배열에 해당 키가 없으면 폭발하지 않는 방식으로 링크를 정의하는 정적 방법이 있습니까?

답변

7

PHP5 "마법"__get() 방법을 사용하십시오. 마법 __get, __set를 사용

public class TestClass { 
    private $data = array(); 

    // Since you're using PHP5, you should be using PHP5 style constructors. 
    public function __construct() { 
     $this->data['firstValue'] = "cheese"; 
    } 

    /** 
    * This is the magic get function. Any class variable you try to access from 
    * outside the class that is not public will go through this method. The variable 
    * name will be passed in to the $param parameter. For this example, all 
    * will be retrieved from the private $data array. If the variable doesn't exist 
    * in the array, then the method will return null. 
    * 
    * @param string $param Class variable name 
    * 
    * @return mixed 
    */ 
    public function __get($param) { 
     if (isset($this->data[$param])) { 
      return $this->data[$param]; 
     } else { 
      return null; 
     } 
    } 

    /** 
    * This is the "magic" isset method. It is very important to implement this 
    * method when using __get to change or retrieve data members from private or 
    * protected members. If it is not implemented, code that checks to see if a 
    * particular variable has been set will fail even though you'll be able to 
    * retrieve a value for that variable. 
    * 
    * @param string $param Variable name to check 
    * 
    * @return boolean 
    */ 
    public function __isset($param) { 
     return isset($this->data[$param]); 
    } 

    /** 
    * This method is required if you want to be able to set variables from outside 
    * your class without providing explicit setter options. Similar to accessing 
    * a variable using $foo = $object->firstValue, this method allows you to set 
    * the value of a variable (any variable in this case, but it can be limited 
    * by modifying this method) by doing something like: 
    * $this->secondValue = 'foo'; 
    * 
    * @param string $param Class variable name to set 
    * @param mixed $value Value to set 
    * 
    * @return null 
    */ 
    public function __set($param, $value) { 
     $this->data[$param] = $value; 
    } 
} 

, 당신은 여전히 ​​단일 배열의 모든 값을 저장하는 동안 변수는 클래스에 설정하는 방법을 __isset 생성자를 제어 할 수 있습니다 : 그것은과 같이 작동합니다.

희망이 도움이됩니다.