Skip to main content
GameDev.net gamedev.net
🔒 Locked

[PHP] Question about variable variables.

Started by GenmaC Sep 4, 2003 at 1:39 PM 1 replies 350+ views
Original Post
GenmaC
GenmaC
// for loop starts here
global ${$this->var_names[$i]};
${$this->var_names[$i]} = $this->get_information($i);
// end of for loop
 
Above is the relevant portion of the code I''m having a problem with. Basically, within my class I have two arrays: var_names, which is an array of names for the variables to be set, and another array of arrays which holds the information the variables should be set to. So what I want to do is create a variable from each element in var_names, and then set the newly created variable to one of the elements (using my get_information function). My problem is that while the newly created variables are being set to the correct values, the newly created variables themselves are identified as "Array" instead of the names I am assigning them. Any help would be appreciated, and I''ll gladly provide more information (or hell, the whole source, since this is an opensource project) upon request. Thanks.
fenghus
fenghus
As far as i can tell, your code is correct. This might be a more readable variation:

$cnt = count($this->var_names);
for($i=0;$i<$cnt;$i++) {
$vname = $this->var_names[$i];
$$vname = $this->get_information($i);
}

If your variables turn out to be of type Array, either get_information() returns an array or var_names contains entries such as "myvarname[]"
UfoZ
UfoZ
If you want to set global variables by name, a cleaner approach is using the $GLOBALS array.


$GLOBALS[$this->var_names[$i]] = $this->get_information($i);

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.