frosty
frosty

Reputation: 2851

Use variable declared inside function outside of it

In db.php:

function connect() {
    // vars declared
    $conn = new mysqli($servername, $username, $password, $database);
}

In another file.php:

require_once('db.php');
connect();
$stmt = $conn->prepare("...");

How do I use $conn outside of the function? All of the answers online refer to the inverse of this. I tried global but didn't seem to work for me.

Upvotes: 0

Views: 87

Answers (3)

Jinksy
Jinksy

Reputation: 451

You may want to use 'static' keyword like this:

function connect() {
    static $conn;
    if (is_null($conn)) {
        $conn = new mysqli($servername, $username, $password, $database);
    }
    return $conn;
}

Have a look in here: http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static

Regards.

Upvotes: 1

Rohit Kumar
Rohit Kumar

Reputation: 1958

You can declare it ouside and access it globally

$conn;
function connect() {
    // vars declared
    global $conn;
    $conn = new mysqli($servername, $username, $password, $database);
}

Upvotes: 0

Mantas
Mantas

Reputation: 4296

Just return it from function and assign to variable.

function connect() {
    // vars declared
    return new mysqli($servername, $username, $password, $database);
}

require_once('db.php');
$conn = connect();
$stmt = $conn->prepare("...");

Upvotes: 3

Related Questions