2015-05-19 235 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将是一个数组。 –