1

I'm trying to dynamically select a property from an object, but I'm not sure how to accomplish this.

$prop = '12345';
$object->$prop

in effect trying to recreate this:

$object->12345
3
  • 2
    what is the question here? You have answered your question $object->$pro is the correct way of doing it Commented May 8, 2014 at 4:35
  • 1
    the above code should work Commented May 8, 2014 at 4:36
  • 2
    @Guns LOL really? Outsmarted myself! Commented May 8, 2014 at 5:16

1 Answer 1

1

You need to use the curly braces if you want to access that way..

$myobject = new stdClass;
$prop = '12345';
$myobject->$prop = $prop;
echo $myobject->{12345}; //"prints" 12345

or simply echo $myobject->$prop will do.

If you access it as echo $myobject->12345;, below error will be thrown.

PHP Parse error: syntax error, unexpected '12345' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

Sign up to request clarification or add additional context in comments.

Comments

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.