好了,这里是我的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