我认为对于大多数 PHP 人来说,这将是一个相当基本的问题。假设我有这个文件可以使用数据库:
<?php
define("DB_HOST", "localhost");
define("DB_NAME", "dbname");
define("DB_USER", "admin");
define("DB_PASSWORD", "abcdefg");
$connection;
$result;
function connectDatabase() {
global $connection;
if(isset($connection)) return;
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ")");
}
}
function queryDatabase($query) {
global $connection, $result;
$result = mysqli_query($connection, $query);
if(!$result) {
die("Database query failed");
}
else {
return $result;
}
}
function releaseResult() {
global $result;
mysqli_free_result($result);
}
function closeConnection() {
global $connection;
mysqli_close($connection);
}
?>
假设我这样称呼它:
<?php
require_once("db_connection.php");
function createNavigation() {
connectDatabase();
$query = "SELECT * ";
$query .= "FROM subjects ";
$query .= "ORDER BY position ASC";
$result = queryDatabase($query);
while($subject = mysqli_fetch_assoc($result)) {
//do something
}
releaseResult();
}
?>
问题是 - 我真的必须在 createNavigation 函数中释放本地 $result 还是没有必要?
mysqli_free_result 到底有什么用?来自其他 OOP 语言,我了解释放/销毁/禁用/清空对象、GC、内存管理等,但考虑到脚本只运行一次,返回一些内容并完成,我有点困惑它在 PHP 中的好处。谢谢!