13

I would like to do something like this: echo $myObject->value_$id but I don't know proper syntax and I'm not sure if it is possible.

$id is some PHP variable, for example has value 1. In the end, I would like to get $myObject->value_1 but the number part (1) should be dynamic.

3
  • I'm curious how to do this in way using -> Commented Dec 28, 2011 at 15:14
  • $myObject->myArray["element"]; or $myObject->myArray[$id];. I think using arrays is a better way to do this anyways. But, what exactly do you want to do? Commented Dec 28, 2011 at 15:16
  • Ah, ok, now I understand that 'array thing' you were talking about Commented Dec 28, 2011 at 15:40

3 Answers 3

24

The feature is called variable properties:

<?php

$myObject = (object)NULL;
$myObject->value_1 = 'I am value nr 1';

$id = 1;
echo $myObject->{"value_$id"};
Sign up to request clarification or add additional context in comments.

3 Comments

I have never seen before casting NULL to an object ^^ Interesting idea ;-)
@Armin - Hang around StackOverflow for a while and you'll see weirder things :)
Been writing PHP for quite a while and haven't seen this done before. You learn something new every day I suppose. Thank you very much for this knowledge. :)
5

This works:

$variableName = 'value_whatever_1337';
echo $myObject->$variableName;

2 Comments

And can't I join variable and string in the second line somehow?
You could, but this is not the recommended way if you want to keep your code clear and easy to read!
4
$name = "value_" . $id;
echo $myObject->$name;

1 Comment

And can't I join variable and string in the second line somehow?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.