Page 1 of 1

accessing class member dynamically

Posted: Tue Nov 18, 2008 8:33 am
by yacahuma
I want to access part of a class dynamically(the portion of the class is determined at run time). I cant get eval to give me the right answer and I though I could just use the code bellow. But is not working. Any ideas?

Code: Select all

 
echo $this->data->member1->field1;  //OK
 
$field = 'member1->field1';
echo $this->data->$field->field1; //ERROR
 

Re: accessing class member dynamically

Posted: Tue Nov 18, 2008 8:43 am
by VladSun

Code: Select all

$field = 'member1->field1';
I don't think you can do this.

also, I think you need:

Code: Select all

echo $this->data->member1->field1;  //OK
 
$field = 'member1';
echo $this->data->$field->field1;

Re: accessing class member dynamically

Posted: Tue Nov 18, 2008 8:55 am
by yacahuma
the idea is to be able to map a field with a field in an object for example

Code: Select all

 
$field_array = array(
'FIELD1'=>'customer->name',
'FIELD2'=>'car->insurance->debt->number'
);
 
imagine that I have classes that match the above path. then in my code I could do
$field = $field_array['FIELD1'];
echo $this->data->$field;
 
Since there could be objects inside objects, I need to be able to use the arrow(->)
 

Re: accessing class member dynamically

Posted: Tue Nov 18, 2008 9:17 am
by yacahuma
Well ,I was using eval wrong

this works

Code: Select all

 
eval("\$value = \$this->data->{$this->targetClass}->$fld;");
 
If someone knows a better way?