2008-09-19 77 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()方法。它的工作就像這樣:

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; 
    } 
} 

使用魔法__get__set__isset構造將允許你控制你怎麼想的變量要在類中設置,同時仍然存儲在一個單一陣列中的所有值。

希望這會有所幫助:)