Making global var from inside a function in PHP

后端 未结 3 1474
栀梦
栀梦 2021-01-23 08:16

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)

3条回答
  •  再見小時候
    2021-01-23 08:50

    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;
        // ...
    }
    

提交回复
热议问题