我遇到了一个问题,用户已经超过了“max_user_connections”活动连接
这是因为我将函数用于网站功能,每个函数都包含一个
$mysqli = connect();虽然同时,每个函数在函数结束时关闭mysqli。
mysqli_close($mysqli);I不希望将$mysqli作为函数的参数,因为该函数是动态的,在每个函数调用中包含它是很麻烦的。
connect()函数只包含:
$mysqli = new mysqli(...);
return $mysqli;我认为抛出错误是因为函数有时会根据用户的输入和先决条件调用自己进行不同的执行。即使mysqli在函数的末尾关闭..。
我想知道是否有一种在全球范围内重复使用$mysqli连接的方法.
我不知道我是否已经完全解释了自己,所以如果你需要更多的信息,请留下评论。
发布于 2022-09-21 11:30:36
有许多技术只实例化一个变量一次。这是一个反解决方案。请不要使用这里列出的解决方案!
静态变量
如果只希望在第一次调用函数时实例化变量,则可以使用静态变量。
function foo(){
static $mysqli;
if ($mysqli === null) {
$mysqli = connect();
}
// call the same function in recursive mode and the same connection will be reused
foo();
// do not close the connection manually!
}这是一个糟糕的解决方案,因为您的函数手动获取依赖项。您不应该创建具有副作用或多目标的函数。不应从执行其他操作的函数中调用连接的函数。这导致了噩梦般的代码,这就是为什么你现在有这个问题。
使用单例
单例不利于测试和代码可读性。每当您需要更改依赖项时,都需要更改使用单例的所有位置。要更好地解释它们为什么不好,请参阅What are drawbacks or disadvantages of singleton pattern?。
使用全局
全局代码对代码的可维护性非常不利。他们永远是程序员的祸根。这正是我们进行封装和依赖注入的原因。
使用全局变量与使用静态变量非常相似,只是副作用现在是全局的。
function foo(){
// declare a variable as global.
// this will instantiate the variable to null if it doesn't exist as a global yet
global $mysqli;
// if it's null, connect
if ($mysqli === null) {
$mysqli = connect();
}
// call the same function in recursive mode and the same connection will be reused
foo();
// do not close the connection manually!
// but if you must close the connection, just set the variable back to null
}不要使用上述任何一种解决方案!这些是不好的不可维护的意大利面代码的例子。程序员的噩梦。这个答案应该只是警告不要做什么!
https://stackoverflow.com/questions/73798327
复制相似问题