2

I have a question about attributes in PHP.

I have various Class with the same attributes, but with with different prefix.

Example:

$attr->a_field;

$attr2->b_field;

So, with another Class I want to access to them.

I tried:

$field = "{$prefix}_field";
$attr->{$field}

and it works perfect. But is any other way to doing this?

I tried also with:

$attr->{$prefix}_field;
$attr->{$prefix}{"_field"};
$attr->"{$prefix}_field";

etc and who I suppose I get PHP's errors

Thanks!

carlos
  • 108
  • 1
  • 10

2 Answers2

1

You can write it directly as $attr->{"{$prefix}_field"}, as shown in the docs.

Matteo Tassinari
  • 17,408
  • 7
  • 58
  • 80
0

You're looking into variable variables

$attr->{$prefix."_field"}
Pedro Lobito
  • 85,689
  • 29
  • 230
  • 253