![]() Join Up! 96812 members and counting! |
|
|||
Variable Variables, PHP, and You
Robert Berkowitz
During a recent project I discovered a totally new concept in programming for myself,
variable variables. I needed to update multiple records from one page. After banging
my head on the wall for quite some time, I stumbled across the variable variable and
all my troubles went away!
Introduction
So, just what the heck is a variable variable anyway? According to the PHP manual,
a variable variable takes the value of a variable and treats that as the name of a
variable. While this may seem pretty straightforward, it can be a little confusing
with so many uses of the word "variable" in one sentence. What the definition simply
states is that you can set a variable -- x equals this -- and then set the variable
variable, meaning you set the value of x as a new variable of x. In this example,
the variable this would equal is cake. In PHP, this would be denoted as follows:
The $$ is the syntax used in PHP for a variable variable. I can now call the two variables $x and $$x two ways.
Both of these will return the string "this is cake". Notice that $$x is written as ${$x}
in echo. This lets PHP know that you are using the variable $$x and not $ and $x.
Still scratching your head? Or maybe you get it, but want a more in depth and actually
useful example? In the next section I will show you how variable variables may be used
to edit multiple records on one page.
Example
Let's say you have a MySQL database that stores link submissions for sites of interest.
In that database there is a table called submissions. The fields in the submissions table are as follows:
SubmissionID PostedBy Link Description Approved
You want to be able to display all the submissions that have been made but are not yet approved in
a table. The editor will then be able to correct any typing mistakes, select the proper radio
button next to each link for approval, and submit them all at once.
First, when you pull the data from the database and display it on the page you must set each name
for every record to be unique. This will enable us to loop through the records and be able to
identify what value goes where once the submit button has been pressed. To do this we do the following:
After the submit button is pressed to we have to loop through all the variables on the page again.
We are able to do this with the $index_count variable we created. Next, we assign the value of
those variables to yet another variable in the second step. This is where variable variables come into play.
I hope this has helped you to understand the basics of variable variables and given you
some ideas of how to use them in future projects. They were pretty confusing to me at
first, but once you get the basic understanding of how variable variables work they're a
piece of cake. Let me know if you have any other questions.
--Robert
|