operator precedence - PHP: Illegal string offset because [] binds tighter than -> -
i new php , had learning experience sharing here others who, me, may need find cause of error , because still don't know solution , sure there syntax haven't found yet need do.
so, problem can demonstrated this:
class sample { protected $foo = array(); public function magicsamplesetfunc($property, $key, $value) { $this->$property[$key] = $value; } } ... $s = new sample(); $s->magicsamplesetfunc('foo', 'somekey', 'someval');
obviously, isn't real code (nor have run it) minimal example explain situation. here have member variable foo array , generic function going try set key , value it. can var_dump $this->$property
, see array, on $this->$property[$key]
line error message: "warning: illegal string offset 'somekey' in ...".
at first though saying 'somekey' illegal string use array offset, didn't make sense. and, if wrap in isset complains. first thing learned if have string in php, can use array access operator character out of string. warning message complaining 'somekey' not valid offset string (because not integer offset). okay, var_dumped $this->$property
, see array, gives? second lesson 1 of operator precedence. array operator "[]" binds tighter indirection operator "->". so, binding of statement like: ( $this-> ( $property[$key] ) )
. so, illegally trying offset string in $property index in $key. wanted offset array in $this->$property
index in $key.
so, come question. third lesson need learn, , haven't figured out yet how override operator precedence issue? tried ($this->$property)[$key]
appears sytax error. there other syntax can use interpreter understand meant do? or, have assign $this->$property
temporary variable first? if do, wouldn't mean actual member variable array not updated? need temp reference or something? what's right syntax situation here? thanks!
this way it: variable name {$property}
when $this->$property[$key]
think php parser gets confused. make sure explicitly state parser variable name $property done using curly braces around variable.
curly braces used explicitly specify end of variable name
class sample { protected $foo = array(); public function magicsamplesetfunc($property, $key, $value) { $this->{$property}[$key] = $value; } } ... $s = new sample(); $s->magicsamplesetfunc('foo', 'somekey', 'someval');
Comments
Post a Comment