accessing class member dynamically

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

accessing class member dynamically

Post 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
 
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: accessing class member dynamically

Post 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;
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

Re: accessing class member dynamically

Post 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(->)
 
User avatar
yacahuma
Forum Regular
Posts: 870
Joined: Sun Jul 01, 2007 7:11 am

Re: accessing class member dynamically

Post 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?
Post Reply