Reputation: 2851
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
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
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
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