目标PHP和键值编码

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

$price = $product->{$price_field};

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

How about using get_object_vars?

$price_field = 'field_'.$product_type.'_price';
$instvars = get_object_vars($product);
$price = $instvars[$price_field];

Actualy it would work as follows.

$product_type = $product->type;


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


$price = $product->$price_field;