2014-12-27 34 views
0

我想知道爲什麼這種行爲在PHP甚至有可能:動態變量創建,爲什麼這甚至可能?

class Quick { 
    public function add_variable($key,$value) { 
     $this->some[$key] = $value; 
    } 
    public function get_variable($key) { 
     return (isset($this->some[$key]))?$this->some[$key]:null; 
    } 
} 

$Quick = new Quick(); 
$Quick->add_variable("test1", 20); 
var_dump($Quick->get_variable("test1")); 

// Output: int(20) 

我遇到了一些問題,這種行爲,我想知道爲什麼這可能嗎?這有什麼用途。

我知道,在PHP變量不必聲明,甚至不是陣列和:$tar["key"] = "some";是完全沒問題的。 但是,當使用對象時,我們正在聲明這些變量及其訪問權限。 這裏發生了什麼?它的公衆清楚......我有點困惑。有什麼見解?

回答

0

爲什麼?因爲它是這樣設計的?動態定義的屬性將始終是公開的。

有什麼用?一個例子是數據模型,其中可以爲每個列動態定義一個屬性,而無需事先定義每一列。

請注意,你只是創建一個屬性some作爲一個數組,沒有什麼聰明的test1這是一個簡單的關聯數組元素;當你想索引你的快速檢索數據,你add_variable()get_variable()方法可以使用魔法__get()__set()

0

能夠動態創建關聯數組實現是非常有用的。下面的示例創建一個索引數組來緩存資源昂貴功能的結果。

class Quick { 
    public function add_variable($key,$value) { 
     $this->some[$key] = $value; 
    } 
    public function get_variable($key) { 
     return (isset($this->some[$key]))?$this->some[$key]:null; 
    } 
    public expensive_calculation($key) { 
     //if the results exist in cache, return from cache 
     $result = $this->get_variable($key); 
     if(!is_null($result)) { 
      return $result; 
     } 

     //do expensive calculation & store in $result 
     $this->add_variable($key,$result); 
     return $result; 
    }  
}