33

If I have an object that contains a property that starts with a % symbol, how can I get its value.

If I use

echo $myobject->%myproperty;

I get an error

Parse error: syntax error, unexpected '%', expecting T_STRING or T_VARIABLE

I know I shouldn't use % in variable names, but it wasn't my doing and I'm stuck with it.

Matt Urtnowski
  • 2,556
  • 1
  • 18
  • 36
  • 2
    Related: [How to access object properties with names like integers?](http://stackoverflow.com/questions/10333016/how-to-access-object-properties-with-names-like-integers) – hakre Mar 31 '13 at 14:44

2 Answers2

109
echo $myobject->{'%myproperty'};
Brad
  • 159,648
  • 54
  • 349
  • 530
  • 2
    Five years old, but still a bad answer, just one line of code. – AbraCadaver Oct 17 '17 at 18:11
  • 4
    @AbraCadaver I don't disagree with you. You should post your own answer with what you were going to edit into mine. – Brad Oct 17 '17 at 18:12
  • No, because the solution is the exact same, I just added some description. This is worse than a _Try this_ `codez` answer. – AbraCadaver Oct 17 '17 at 18:13
  • 4
    May 2018 and this answer is still great. Thanks, no need to add further info, this is crystal clear as it is. – GrafiCode May 30 '18 at 14:37
  • 1
    Trying to access '@attributes' property of a SimpleXMLElement object but it doesnt work. Had to convert object to array to make it work. Weird behaviour. – sba Aug 15 '18 at 09:45
  • 2
    2021 and the answer is still a great. No comment needed for one line of code with one term in it. Works with Twitter endpoints such as $rate_limits->resources->users->{'/users/'} and even with $rate_limits->resources->users->{'/users/:id'} with its slashes and a colon. – Brian Tristam Williams Apr 26 '21 at 02:17
  • @sba To get at attributes of an XML tag, you can use the string value of the attribute as an index. $item->url['href'] – Bryan Cockerham Jun 27 '21 at 13:38
  • 1
    Great answer! The less said the better, good code should speak for itself and not need comments. – dbDev Dec 24 '21 at 01:33
0

I have one more solution to convert object to an array, so that you will not get an error.

I have a symbol - on the object index, so I have used the above solution and got success.

$array = (array) $yourObject;

Reference: http://www.php.net/manual/en/language.types.array.php

Yash Mehrotra
  • 3,032
  • 1
  • 21
  • 24