17

Instead of using

$object->my_property

I want to do something like this

$object->"my_".$variable
1
  • 1
    One thing to keep in mind is that while you can use dynamic variables, it is often preferable to be explicit. It makes refactoring later easier for one. Imagine searching for a property called "my_cat", you would not find that if it is declared dynamically. Commented Jun 10, 2015 at 18:55

2 Answers 2

35

Use curly brackets like so:

$object->{'my_' . $variable}
Sign up to request clarification or add additional context in comments.

Comments

9

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. )

1 Comment

Thanks, if I could give two ticks you'd have one as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.