开发者

create a variable name from a string.. php

Generally I pass an array of parameters to my functions.

function do_something($parameters) {}

To access those parameters I have to use: $parameters['param1']

What I would like to do, is run some sort of logic inside this function on those parameters that converts that array into normal variables.开发者_如何学C My main reasons is just that sometimes I have to pass a whole load of parameters and having to type $parameters['..'] is a pain.

foreach($parameters as $key=>$paremeter) {
    "$key" = $parameter;
}

I thought that might work.. but no cigar!


Use extract():

function do_something($parameters) {
    extract($parameters);

    // Do stuff; for example, echo one of the parameters
    if (isset($param1)) {
        echo "param1 = $param1";
    }
}

do_something(array('param1' => 'foo'));


Try $$key=$parameter.


Just extract the variables from array using extract:

Import variables into the current symbol table from an array

extract($parameters);

Now you can access the variables directly eg $var which are keys present in the array.


There is the extract function. This is what you want.

$array = array('a'=>'dog', 'b'=>'cat');
extract($array);
echo $a; //'dog'
echo $b; //'cat'
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜