Simple Variable Question

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
Pineriver
Forum Commoner
Posts: 50
Joined: Fri Aug 15, 2003 5:24 pm

Simple Variable Question

Post by Pineriver »

Hi,
Obviously this code will generate an error, but might anyone know how to acquire this result?

Code: Select all

$tempvar = 'secondhalf';

$foo.$tempvar = "This is the value that will be put in the var '$foosecondhalf'.";
print "$foosecondhalf"; //would print "This is the value that will be put in the var '$foosecondhalf'."
Thanks
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

${'foo' . $tempvar} = "blahlbah";

for future generations a keyword: metaprogramming
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Huh

Post by neophyte »

I don't get it? Why the braces?..... Can you explain Feyd
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

it has to do with how the variables are replaced and sorted out.. $foo.$tempvar concatenates the string results of 2 variables and returns a string, where mine, concatenates the two into a string before the variable part is hooked.. so a string is passed to the first $ there thus creating the variable.

reading this may help: http://www.php.net/manual/en/language.v ... riable.php
User avatar
neophyte
DevNet Resident
Posts: 1537
Joined: Tue Jan 20, 2004 4:58 pm
Location: Minnesota

Yeah I think I get it...

Post by neophyte »

I've been wondering if there was a way to do this... I found this posted on the variable variables link you put up Feyd. Good practical example of Variable Variables. This takes post variables and names the variable the key name (with a prefix) and assigns its value to it. Great way of going from $_POST['some_variable']="blah" to $some_variable = "blah"... etc....

(Did I over explain that?)

Code: Select all

foreach($_POST as $key => $value) {
       $varname = "frm_".$key;
       $$varname = $value;
}
Thanks Feyd :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

that's basically, a manual [php_man]extract[/php_man] call. :)
User avatar
Lord Sauron
Forum Commoner
Posts: 85
Joined: Tue Apr 20, 2004 5:53 am
Location: Tilburg, NL

Post by Lord Sauron »

By the way, why is this subject categorized under 'Theory and Design'?
Post Reply