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
  • 140
  • 1
  • 12

2 Answers2

1

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

Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81
0

You're looking into variable variables

$attr->{$prefix."_field"}
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268