如何在函数外部使用变量

时间:2014-02-05 06:24:41

标签: php function variables mysqli

我有一个名为 init.php 的初始化文件,我已经为 $db声明了一个名为 mysqli 的变量连接。以下是我的代码。

<?php
    ob_start();
    session_start();

    define('DBHOST', '127.0.0.1');
    define('DBUSER', 'root');
    define('DBPASSWORD', '');
    define('DBNAME', 'mydb');

    $db = new mysqli(DBHOST, DBUSER, DBPASSWORD, DBNAME);

    if ($db->connect_error) {
        header('Location: 404.php');
    }

    require_once 'functions/User.php';
    require_once 'functions/Sanitize.php';

正如您所见,我在功能文件夹中需要 User.php ,在 User.php 文件中我有此代码

<?php
    function login($idnumber, $username, $password) {
        $idnumber = sanitize($idnumber);
        $username = sanitize($username);
        $password = sanitize($password);

        $hashed_password = get_hashed_password($username);
    }

    function get_hashed_password($username) {
        $username = sanitize($username);

        $sql = "SELECT `password` FROM `users` WHERE `username` = ?";

        $stmt = $db->prepare($sql);

        if(!$stmt) {
            echo 'invalid sql statement';
        }

        die();
    }

在get_hashed_pa​​ssword()函数中,我使用了变量$db但是我收到一条错误消息

Notice: Undefined variable: db in D:\xampp\htdocs\sample\functions\User.php on line 15

Fatal error: Call to a member function prepare() on a non-object in D:\xampp\htdocs\sample\functions\User.php on line 15

有人可以帮助我如何在我的任何函数中使用变量$ db?提前谢谢!

2 个答案:

答案 0 :(得分:3)

将$ db称为全局

function get_hashed_password($username) {
    global $db;
    //...
}

答案 1 :(得分:1)

您可以在此功能中使用$GLOBALS

$your_var = "something";
function abc()
{
    $your_var = $GLOBALS['your_var'];

}

更新2:

function get_hashed_password($username) {
        $username = sanitize($username);

        $sql = "SELECT `password` FROM `users` WHERE `username` = ?";
 $db = $GLOBALS['db'];
        $stmt = $db->prepare($sql);

        if(!$stmt) {
            echo 'invalid sql statement';
        }

        die();
    }