Making global var from inside a function in PHP

2020-04-26 06:40发布

问题:

I am trying to define dynamically variables. I am using a function for this, but I don't know how to define the new var as global (because it never created before the function).

is that possible ?

Thanks.


edit

ok, this is what I've built. is it that dangerous ?

function extract_values($row) {
    foreach ($row as $key => $value){
        global $$key;
        $$key = $value;
    }
}

and then I'm trying to make my life easier like that:

$result = mysql_query("SELECT first_name, last_name, address FROM users ORDER BY id ASC");

    while ($row = mysql_fetch_array($result)){
        extract_values($row);
#[do some stuff with the variables.]#
}

I am doing it to save time. instead of creating for each column it's own variable like

$first_name = $row['first_name'];

This function does that for me. I don't see why in this case it might be dangerous.. or as usuall, i am missing something..

回答1:

Try this:

function doSomething() {
  global $x;
  $x = 5;
}

If you prefer to save a couple of bytes, you can use the $_GLOBALS array for this:

$_GLOBALS['x'] = 5;


回答2:

Regarding your edit: It makes your code less understandable.

Actually, there already exists a function that is doing this: extract().

while (($row = mysql_fetch_assoc($result))){
    extract($row);
    // ...
}

extract() is even better, because it lets you specify what should happen if the variable already exists and/or lets you specify a prefix (so you don't overwrite already existing variables with that name). E.g. you could do:

extract($row, EXTR_PREFIX_ALL, 'db');

which would result in $db_first_name etc.

Surly, extract() is also doing some internal work here, but using built-in functions is always better than creating your own.


Another possibility would be to use list():

while (($row = mysql_fetch_row($result))){
    list($first_name, $last_name, $address) = $row;
    // ...
}


回答3:

You can do it in two ways:

Make the variable global using the global keyword:

function fun1() {
        global $foo;
        $foo = 1;
}

Alternatively you can also create an new element in the $GLOBALS array:

function fun2() {

        $GLOBALS['bar'] = 1;
}

Working code

Remember that these are considered bad practice, a function should have local variables invisible outside and should get inputs through the arguments passed. You should avoid getting arguments though global variables and must completely avoid crating global variables.