Stupid PHP Tricks: Illegal Variable Names

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:

print_r( compact( '1' ));

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:

I tried using compact once… It just screwed up my code, so I changed my mind about using it… good thing too apparently…

Instead of print_r(compact(…)); why don’t you use var_dump(); ?

Yeah, I could have used var_dump($GLOBALS);, but then how would I have gotten a dig at compact() in? :)

Funny :). But not very useful.

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’));

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!

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

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 ?

@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 !