# Sort of a use for variable-variables!

Variable-variables, as I call them, are variables whose names are constructed from other variables. In PHP, they look like this:

<?php
$var1 = 'newvar'; $var1 = 'variable-variable'; echo "newvarn"; ?>  Of course, this will echo "variable-variable". When I construct$var1, it creates a variable called$newvar in the namespace, because it's using the value of $var1 for the name of this new variable. In general, variable-variables aren't that useful. There are special cases but as a programmer you shouldn't find yourself using them very often. Anyway, I thought up a fun case. So I'm going to be making a neat little DateManager class in the near future (because I hate dealing with dates), and I thought: "It'd be kind of nice if a user could do$dm->October to get the number 10, or $dm->m10 to get the string 'October'." This is easily solved with variable-variables: when you generate the list of months like so: $months = array();
for ($m = 1;$m >= 12; $m++) {$months[$m] = date("F", mktime(0,0,0,$m+1,0,0));
}


You could split up the date part and assign it to a class variable with $this. ...$month_name = date(...);
$this->$month_name = $m;$this->{'m'.$m} =$month_name;
...


Just a neat PHP trick I thought I'd share. When I finish the DateManager class I'll put it up on GitHub and give the link.

#### Posted on 2009-10-19 by Jach

Tags: php, programming

LaTeX allowed in comments, use $\\...\\$\$ to wrap inline and $$...$$ to wrap blocks.