Monday, September 27, 2010

Dynamic Variables in Php

As you know, you create a variable with a dollar sign followed by a variable name.
Unusually, the variable name can itself be stored in a variable. So, when assigning
a value to a variable
$user = "bob";
is equivalent to
$holder="user";
$$holder = "bob";
The $holder variable contains the string "user", so you can think of $$holder as a
dollar sign followed by the value of $holder. PHP interprets this as $user.
Note You can use a string constant to define a dynamic variable instead of a
variable. To do so, you must wrap the string you want to use for the variable
name in braces:
${"user"} = "bob";
This might not seem useful at first glance. However, by using the
concatenation operator and a loop (see Hour 5, "Going with the Flow"), you
can use this technique to create tens of variables dynamically.
When accessing a dynamic variable, the syntax is exactly the same:
$user ="bob";
print $user;
is equivalent to
$user ="bob";
$holder="user";
print $$holder;
If you want to print a dynamic variable within a string, however, you need to give
the interpreter some help. The following print statement:
$user="bob";
$holder="user";
print "$$holder";
does not print "bob" to the browser as you might expect. Instead it prints the strings
"$" and "user" together to make "$user". When you place a variable within
quotation marks, PHP helpfully inserts its value. In this case, PHP replaces $holder
with the string "user". The first dollar sign is left in place. To make it clear to PHP
that a variable within a string is part of a dynamic variable, you must wrap it in
braces. The print statement in the following fragment:
$user="bob";
$holder="user";
print "${$holder}";
now prints "bob", which is the value contained in $user.
Listing 4.1 brings some of the previous code fragments together into a single script
using a string stored in a variable to initialize and access a variable called $user.


Dynamically Setting and Accessing Variables
1: <html>
2: <head>
3: <title>
Dynamically setting and accessing variables</title>
4: </head>
5: <body>
6: <?php
7: $holder = "user";
8: $$holder = "bob";
9:
10: // could have been:
11: // $user = "bob";
12: // ${"user"} = "bob";
13:
14: print "$user<br>"; // prints "bob"
15: print $$holder; // prints "bob"
16: print "<br>";
17: print "${$holder}<br>"; // prints "bob"
18: print "${'user'}<br>"; // prints "bob"
19: ?>
20: </body>
21: </html>

No comments:

Post a Comment