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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line