27

I'm working on an existing code base and got back an object with an attribute that starts with a number, which I can see if I call print_r on the object.

Let's say it's $Beeblebrox->2ndhead. When I try to access it like that, I get an error:

Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$'

How can I get that attribute?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Nathan Long
  • 122,748
  • 97
  • 336
  • 451
  • I know that you work on existing code, but for the sake of completeness I want to add, that one should avoid using variables that enforces to use the curly bracket syntax. "Normal" use of variables names is just better known and easier to read. – Felix Kling Jul 13 '10 at 20:24
  • I just [answered](http://stackoverflow.com/a/10333200/50079) a similar question; if you are having problems with an attribute that is **all numbers** you will find the solution there. – Jon Apr 26 '12 at 13:08

3 Answers3

50

What about this :

$Beeblebrox->{'2ndhead'}


Actually, you can do this for pretty much any kind of variable -- even for ones that are not class properties.

For example, you could think about a variable's name that contains spaces ; the following syntax will work :

${"My test var"} = 10;
echo ${"My test var"};

Even if, obviously, you would not be able to do anything like this :

$My test var = 10;
echo $My test var;


No idea how it's working internally, though... And after a bit of searching, I cannot find anything about this in the PHP manual.

Only thing I can find about {} and variables is in here : Variable parsing -- but not quite related to the current subject...


But here's an article that shows a couple of other possiblities, and goes farther than the examples I posted here : PHP Variable Names: Curly Brace Madness

And here's another one that gives some additionnal informations about the way those are parsed : PHP grammar notes

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
6

I actually found out the answer from a coworker before I asked this, but couldn't find it on Google, so I wanted to post it here in case others have the same problem.

I can access that attribute like so:

$Beeblebrox->{'2ndhead'}

It's not really legal to have an attribute or variable that begins with a number, but somehow a dynamic reference like this makes it possible. Seems like a weird loophole in the language to me.

Nathan Long
  • 122,748
  • 97
  • 336
  • 451
1

You can do something like this too:

$aux = '2ndhead';
$Beeblebrox->$aux;
David Buck
  • 3,752
  • 35
  • 31
  • 35