1

I have an object and can access one of its properties by

$book = new Book(); print $book->price;

I can also call

 $prop = "price"; print $book->$prop.

But I cannot figure out how to call in a mixed way, it gives error:

$book->id_$prod

as a shortened of $book->id_products, being $prod = "products".

Cesar
  • 514
  • 1
  • 5
  • 16

2 Answers2

1

Mix the 2 first options.

$prop = 'id_'.$prod;
$book->$prop;
Jonnix
  • 4,121
  • 1
  • 30
  • 31
1
$book = new Book(); 
$id_prod = "id_$prod";
print $book->$id_prod;
Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
  • Is this the only way? No possibility of using {} or something? It reminds me of dereferencing of objects, like $object->method()[0] which was incorrect until PHP 5.4 I think, you should make $tmp =$object->method(), and later access $tmp[0]. – Cesar Apr 28 '16 at 14:57
  • yes, you could also do print $book->{"id_$prod"}; – Tudor Constantin Apr 28 '16 at 15:03