2015-05-19 229 views
1

我有一個對象,其公共屬性主要是數組。我已經寫了下面的兩個功能:將值賦給數組的對象屬性

public function updateProperty($property, $key, $value) { 
    if ($key!=null) $this->$property[$key]=$value; 
    else $this->$property=$value; 
} 

public function getProperty($property, $key=null) { 
    if ($key!=null) return $this->$property[$key]; 
    else return $data; 
} 

當我嘗試使用這些功能,我總是得到以下警告:

警告:非法串偏移「身份證」

如果我將getProperty函數更改爲以下版本,那麼一切正常,但我無法弄清楚如何更改updateProperty。爲什麼我得到這個警告?

public function getProperty($property, $key=null) { 
    $data=$this->$property; 
    if ($key!=null) return $data[$key]; 
    else return $data; 
} 
+0

你已經定義了'公共財產$ =陣列();'?另外,不需要將$ property傳遞給函數。在嘗試返回它之前,還要檢查'isset()'。 – AbraCadaver

+0

我已經定義了public $ datafields = array();我用下面的方法使用函數:$ class-> getProperty('datafields','firstData'); –

回答

1

假設你有一個類屬性$datafields,你叫喜歡$class->getProperty('datafields','firstData');你的方法,那麼你需要,你都表現出了可變特性,但是您需要{}消除歧義,因爲它使用索引來訪問數組:

return $this->{$property}[$key]; 

和:

$this->{$property}[$key] = $value; 
+0

是的,這種方式,它的工作原理,謝謝:) –

0

public function updateProperty($property, $key, $value) { if ($key!=null) $this->$property[$key]=$value; else $this->$property=$value; }

這裏,$value是您希望將$property數組指定爲$key的新值。

不知道你爲什麼要這樣做,但是當你說:else $this->$property = $value時,你引用的是$property而不是array。所以在這之後$property不再是一個數組。

假設你多次調用這個方法,一旦$property失去了它作爲一個數組的位置,併成爲一個單純的值,它將嘗試在隨後的調用中更新$property[$key]。這可能是它抱怨非法抵消的原因。

我只是想知道,如果你能做到這一點,而不是:

public function updateProperty($property, $key, $value) { 
    if ($key!=null) 
     $this->$property[$key]=$value; 
} 
+0

因爲如果我沒有指定一個$鍵,我設置或檢索整個屬性。如果未指定$ key,則大多數時間$ value將是一個數組。 –