Making global var from inside a function in PHP

后端 未结 3 1473
栀梦
栀梦 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:31

    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;
    
    0 讨论(0)
  • 2021-01-23 08:41

    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.

    0 讨论(0)
  • 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;
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题