views:

47

answers:

4

Hi Guys. In some part of my code I need something like this:

$product_type = $product->type;
$price_field = 'field_'.$product_type.'_price';
$price = $product->$$price_field;

In other words I need kind of KVC - means get object field by field name produced at the runtime. I simply need to extend some existing system and keep field naming convention so do not advice me to change field names instead.

I know something like this works for arrays, when you could easily do that by:

$price = $product[$price_field_key].

So I can produce key for array dynamically. But how to do that for objects? Please help me as google gives me river of results for arrays, etc... Thank you

+2  A: 

Sorry Guys. It was much easier than I thought. Hopefullty it will help someone. Simply put:

$price_field = 'field_'.$product_type.'_price';
$price = $product->$price_field;

So you can use varialbe to get object field in Php.

I went to far with those $$ ;-)

Regards

Lukasz
FYI, using $$ resolves the contents of the variable. e.g., `$a = 'b'; $b = 'key'; echo $foo->$$a` is the same as `$foo->key` in this example.
konforce
+1  A: 

How about using get_object_vars?

$price_field = 'field_'.$product_type.'_price';
$instvars = get_object_vars($product);
$price = $instvars[$price_field];
Frank Shearar
actualy this looks more like a hack ;-) but i like it +1
streetparade
+2  A: 
$price = $product->{$price_field};
Oblio
+1  A: 

Actualy it would work as follows.

$product_type = $product->type;


$price_field = "field_".$product_type"._price";


$price = $product->$price_field;
streetparade
Thank You - it was so easy. Too easy so I had not even try it....
Lukasz