开发者

dynamically put together a variable from other variables in php

I was wondering if you can construct a PHP variable from another variable.

I want to build a dynamic variable based on the output of another variable.

$cf = new RecursiveDirectoryIterator(dirname(__DIR__) . DS . "configuration");

foreach (new RecursiveIteratorIterator($cf) as $filename => $file) {
    if ($cf->getFilename() != "." && $cf->getFilename() != "..") {
        $ex = explode(".", $filename);
        $_.$ex[0] = parse_ini_file($filename, true);
    }
}

in that code above I want to look through my configuration folder and making ouputing something like this.

Lets say we have db.ini, and theme.ini in the configuration folder

so the output would hopeful开发者_开发问答ly look like

$_db = parse_ini_file("db.ini", true);
$_theme = parse_ini_file("theme.ini", true);

I thought maybe concatenating variables together I could make a new variable ;-)

The scenario is that I want to dump as many .ini files into my configuration folder and have my script dynamically make the $_ variables for me with the parse_ini_file function loaded for that file.

or am I just nuts?


Dynamic Variables

What you want to do is possible, they are better known as variable variables:

http://php.net/manual/en/language.variables.variable.php

For example

$sql = "my query";
$variable = "sql";
echo ${$variable};

Output

my query

So for your example, just change it to

$_{$ex[0]} = parse_ini_file($filename, true);

A better Way

The inherent problem with that though is that it's going to be much harder to keep track of your ini files and what variable they are stored in. A much cleaner method is to use associative arrays.

http://au.php.net/manual/en/function.array.php

So your code would look like this:

$name = pathinfo($filename, PATHINFO_FILENAME); //mildly more accurate then explode
$ini[$name] = parse_ini_file($filename, true);

then after your look just print_r $ini to see the results

print_r($ini);


Try

$name = '_' . $ex[0];
$$name = parse_ini_file($filename, true);


You could do this:

// Inside the loop.
$ex = explode(".", $filename);
$variable = '_' . $ex[0];
$$variable = parse_ini_file($filename, true);

This would do what you want. However, be aware that if $ex[0] is something that's not a syntactically-valid PHP variable name (like "foo.bar") then the variable will be inaccessible except through the dynamic-variable mechanism ($varname = "foo.bar"; $value = $$varname;).

Also, make sure that you trust the INI file you're reading, since this has the potential to clobber your own variables and overwrite them with other data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜