Jump to content

Numbers in variable names?


redwall_hp
 Share

Recommended Posts

Conventional PHP wisdom states that PHP variables can't start with a number or any character other than an alphabetical letter. But when you deal with things objects returned from database queries, parsed API XML results, etc, you sometimes end up with something like this:echo $doc->resultset_web->result->0->title;What the heck are you supposed to do then? It returns a "Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$' in..." So obviously the first thing I tried was to put curly braces around the zero like this: {0}. Nope. Now the echo doesn't output anything.What's the best thing to do in scenarios like this? I've run into this problem twice in as many days.Here's the object structure (via print_r) that I had in one of the scenarios (mainly just playing around with the new Yahoo BOSS API, instead of working on something important, like the other project I had an issue with).

SimpleXMLElement Object(	[@attributes] => Array		(			[responsecode] => 200		)	[nextpage] => /ysearch/web/v1/iphone?appid=(APIKEY-REMOVED)&format=xml&start=10	[resultset_web] => SimpleXMLElement Object		(			[@attributes] => Array				(					[count] => 10					[start] => 0					[totalhits] => 33374083					[deephits] => 983000000				)			[result] => Array				(					[0] => SimpleXMLElement Object						(							[abstract] => iPhone is a revolutionary new mobile phone that allows you to make a call by ... Guided Tour Get a closer look at all the features of iPhone. Watch video ...							[clickurl] => http://us.lrd.yahoo.com/_ylc=X3oDMTRrOTJsMHJkBGFwcGlkAzBPZlNvdUhWMzRHcjF2YXA3UWlCaVNqM2RRTVRGVHBwbGtoVnBybHNaNXpONG90clBzYklUbzdFTVpuanIxUl9PUS0tBHBvcwMwBHNlcnZpY2UDWVNlYXJjaFdlYgRzcmNwdmlkA0dFYUJIVVNPNXE4RWt5amt0Q2E0TGdEWVN0QVFWMGgzazRBQUJkX1o-/SIG=111fl1onm/**http%3A//www.apple.com/iphone/							[date] => 2008/06/09							[dispurl] => www.apple.com/iphone							[size] => 28640							[title] => Apple - iPhone							[url] => http://www.apple.com/iphone/						)*SNIP*

Link to comment
Share on other sites

If you look closely, result is an array, so what you need instead is:

echo $doc->resultset_web->result[0]->title;

XML doesn't allow names of elements and attributes to start with a number, and most other APIs that allow such dynamic object creation also don't allow numbers as a first character.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...