connect_db.php:
<?php
$servername = "1.1.1.1";
$username = "root";
$password = "nope, not making this public :P";
$dbname = "seminarfach";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
//$conn = new mysqli(null, $username, $password, $dbname, null, '/cloudsql/seminarfach-abi-links:data');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "<p>Connected successfully</p>";
// Set charset to UTF-8
if (!$conn->set_charset("utf8")) {
printf("Error loading character set utf8: %s'n", $conn->error);
exit();
}
function TuckTheTorld() {
$conn->close();
}
?>
这是连接到我的数据库的文件,在需要连接的文件中使用require "connect_db.php";
调用它。现在我想创建一个函数,该函数被调用以关闭与数据库的连接。这就是TuckTheTorld函数。我这样命名是为了确保我不会使用任何关键字或过度使用任何其他函数。
问题是,当我调用TuckTheTorld()
时,我会得到以下错误:
Fatal error: Call to a member function close() on a non-object in path_to_file'connect_db.php on line 26
为什么我会出现这个错误?
您需要使用global
关键字将$conn
对象导入函数命名空间(函数命名空间中没有名为$conn
的内容,因为$conn
位于全局文件命名空间中)。
只需将您的功能替换为:
function TuckTheTorld() {
global $conn;
$conn->close();
}
这现在应该对你有效了。