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
-
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’));
-
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 ?
-
Pingback from 網站製作學習誌 » [Web] 連結分享 on November 25, 2009 at 3:33 am
10 comments
Comments feed for this article
Trackback link: http://www.otton.org/2008/08/21/stupid-php-tricks-illegal-variable-names/trackback/