dongming0505 2014-02-14 20:12
浏览 44
已采纳

PHP全局变量范围

I have a helper file that contains quite a few functions, but no "main" function. Each of these helper functions requires a database connection. To improve code maintainability, I'd like to put the variable that holds the database connection in a global state (outside of any of the functions) such that each function has visibility to it and can use it in their mysql calls. Here is what I mean:

$path = $_SERVER['DOCUMENT_ROOT'];
$connection = $path . '/scripts/connection.php';
include ($connection); // this initializes the variable '$link'

function getLocation ($id) {
    $sql = "SELECT name FROM Locations WHERE id=$id";
    $result = mysqli_query($link, $sql);
    if (!$result) { return -1; }
    $row = mysqli_fetch_array($result);
    mysqli_close($link);
    return $row['name'];
}

function getGroupID($group_id) {
    $sql = "SELECT id FROM Groups WHERE group='$group_id'";
    $result = mysqli_query($link, $sql);
    if (!$result) { return -1; }
    $row = mysqli_fetch_array($result);
    mysqli_close($link);
    return $row['id'];
}

// and many other similar functions

I'd rather not put those three global lines inside of each function since then I have to repeat code over and over, but this method has no global scope. I could probably look into passing the $link variable in as an argument, but that would require refactoring a LOT of function calls. I know that some frown on global variables like this, but in this case it is my simplest resolution.

As an aside, if I replace the three global lines with this: include '../scripts/connection.php' my code works fine, but then I lose some of the relative referencing flexibility. I don't understand why the code that I post here operates differently.

Is there a way that I can declare this $connection variable globally?

Thank you.

  • 写回答

2条回答 默认 最新

  • dongwan5381 2014-02-14 20:15
    关注

    Put:

    global $link;
    

    at the beginning of each function.

    Another way to do this is to define a function or class that opens the connection and returns the link. The connection can be a static variable in the function; if it's already set it doesn't reopen the connection:

    function get_db_conn () {
        static $link;
    
        if ($link) {
            return $link;
        }
        $link = mysqli_connect(...);
        return $link;
    }
    

    Then all your other functions can start with:

    $link = get_db_conn();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号