Reputation: 3867
I have an object which public properties are mostly arrays. I've written the following two functions:
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;
}
When I try to use these functions I always get the following warning:
Warning: Illegal string offset 'id'
If I change the getProperty function to the below version, everything works fine there, but I can't figure out how to change the updateProperty too. Why am I getting this warning?
public function getProperty($property, $key=null) {
$data=$this->$property;
if ($key!=null) return $data[$key];
else return $data;
}
Upvotes: 1
Views: 86
Reputation: 78994
Given that you have a class property $datafields
and you call your method like $class->getProperty('datafields','firstData');
then you need a variable property as you have shown, however you need {}
to disambiguate since it accesses an array using the index:
return $this->{$property}[$key];
And:
$this->{$property}[$key] = $value;
Upvotes: 1
Reputation: 3128
public function updateProperty($property, $key, $value) {
if ($key!=null) $this->$property[$key]=$value;
else $this->$property=$value;
}
Here, $value
is the new value you want to assign that $key
of the $property
array to.
Not sure why you're doing this, but when you say: else $this->$property = $value
, you're referencing $property
to a value, rather than an array
. So after this point $property
is no more an array.
Assuming you're calling this method multiple times, once $property
lost it's position as an array and became a mere value, it will try to update $property[$key]
in subsequent calls. This could be the reason why it's complaining about the illegal offset.
I'm just wondering if you can do this instead:
public function updateProperty($property, $key, $value) {
if ($key!=null)
$this->$property[$key]=$value;
}
Upvotes: 0