Guesser
Guesser

Reputation: 1857

PHP dynamic name for object property

Instead of using

$object->my_property

I want to do something like this

$object->"my_".$variable

Upvotes: 17

Views: 10280

Answers (2)

Madara's Ghost
Madara's Ghost

Reputation: 174957

Use curly brackets like so:

$object->{'my_' . $variable}

Upvotes: 35

raina77ow
raina77ow

Reputation: 106385

How about this:

$object->{"my_$variable"};

I suppose this section of PHP documentation might be helpful. In short, one can write any arbitrary expression within curly braces; its result (a string) become a name of property to be addressed. For example:

$x = new StdClass();
$x->s1 = 'def';

echo $x->{'s' . print("abc\n")};
// prints
// abc
// def

... yet usually is far more readable to store the result of this expression into a temporary variable (which, btw, can be given a meaningful name). Like this:

$x = new StdClass();
$x->s1 = 'def';

$someWeirdPropertyName = 's' . print("abc\n"); // becomes 's1'.
echo $x->$someWeirdPropertyName;

As you see, this approach makes curly braces not necessary AND gives a reader at least some description of what composes the property name. )

P.S. print is used just to illustrate the potential complexity of variable name expression; while this kind of code is commonly used in certification tests, it's a big 'no-no' to use such things in production. )

Upvotes: 9

Related Questions