From the PHP manual:
A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus:
'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*’
In other words, variable names can’t begin with a numeral. However there are a couple of ways to slip an illegal variable name into the symbol table:
$var = '1';
$$var = 'hello world';
or
${'1'} = 'hello world';
You can prove to your own satisfaction that the variables really exist with PHP’s rather obscure compact() function:
Please note: if you use any of this in production code - and that includes compact() - I will come to your house and beat you with something heavy.
Tags: php
9 comments
Comments feed for this article
Trackback link
http://www.otton.org/2008/08/21/stupid-php-tricks-illegal-variable-names/trackback/
August 22, 2008 at 3:25 am
SeanJA
I tried using compact once… It just screwed up my code, so I changed my mind about using it… good thing too apparently…
August 22, 2008 at 5:14 am
Kia Kroas
Instead of print_r(compact(…)); why don’t you use var_dump(); ?
August 22, 2008 at 10:49 pm
david
Yeah, I could have used
var_dump($GLOBALS);, but then how would I have gotten a dig atcompact()in? :)August 22, 2008 at 11:43 pm
Mike Borozdin
Funny :). But not very useful.
August 23, 2008 at 9:46 am
Dav
Dude, what’s wrong with compact()? Can be used to greatly clean up code in Frameworks like Cake. :o)
$this->set(compact(’data’, ‘moredata’, ‘evenmoredata’));
August 24, 2008 at 7:57 pm
Mads Skovbjerg Paldam
This odd piece of apparently useless information makes for a nice trick-question in the “knowing absolutely everything there is to know about PHP quiz”… Thanks!
August 25, 2008 at 2:24 pm
Q
oh dear… compact() *gah*
it ranks up there or rather down there with eval()
thanks for adding the following comment to ur post:
“Please note: if you use any of this in production code - and that includes compact() - I will come to your house and beat you with something heavy.”
I hope your readers take careful note… and the world cringes
December 29, 2008 at 11:18 pm
SayB
Hey Guys, I’ve noticed this weird behavior with php’s compact function. It simply does not work with variables that either have underscore in the name OR if they have one or more letters in caps or both. For example, $my_name won’t work, $MyName won’t work either but $myname works fine - anybody got a clue ?
December 29, 2008 at 11:21 pm
SayB
@Dav - FYI I say this after experimenting in Cake. It sure was swell not having to write all those dreaded $this->set() statements for each var :( - doh !