好了,這裏是我的Properties
基類的一個片段,即在大多數在我的應用程序的類的擴展:爲什麼直接訪問數組不可能使用magic __set()方法?
class Properties {
protected $properties_arr = array();
/**
* Magic function to be able to access the object's properties
* @param string $property
*/
public function __get($property) {
if (array_key_exists($property, $this->properties_arr)) {
return $this->properties_arr[ $property ];
}
return $this->getUndefinedProperty($property);
}
/**
* Magic function to be able to access the object's properties
* @param string $property
* @param mixed $value
*/
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->setProtectedProperty($property);
}
$this->properties_arr[ $property ] = $value;
}
這是很基本的,有什麼不妥的,但我運行到一個我以前遇到過幾次的問題,就是你無法通過__get方法對array
屬性執行某些操作。
這樣做,例如:
$MyClass = new Properties();
$MyClass->test = array();
$MyClass->test['key'] = 'value';
你所期望的$MyClass->test
陣列包含一個項目,但它仍然是一個空的數組!現在我知道我可以通過僅僅分配一個已經在其中的項目來解決它,但我真的很想知道這是爲什麼(以及是否有更好的解決方案)。
謝謝!
什麼是'屬性:: setProtectedProperty($ var)'? – binaryLV
只是一個引發'Exception'的內部方法,但可以由子類重寫以定製行爲。你認爲這可能與問題有關嗎?在遇到問題的課堂上,我不會壓倒它。 – Rijk
也許不,不應該是個問題。請參閱@彼得的答案,它適用於我。沒有它,我得到了PHP錯誤「*注意:重載屬性的間接修改Test :: $ foo沒有任何作用*」(你是否啓用了錯誤報告?) – binaryLV