gpt4 book ai didi

PHP 析构函数显示错误?

转载 作者:行者123 更新时间:2023-11-29 12:19:02 24 4
gpt4 key购买 nike

我的类中连接到数据库的析构函数中显示错误,我尝试删除析构函数中的变量,但它也显示错误。这是代码:

class DB_CONNECT {
function __construct() {
$this->connect();
echo "connected succesfully";
}
function __destruct() {
$this->close();
}

function connect() {
require_once __DIR__ . '/db_config.php';

$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE)
or die(mysqli_error());
if($con){
echo "connected succesfully";
}
return $con;
}

function close() {
mysqli_close($con);
}
}

并且有错误消息:

mysqli_close() expects parameter 1 to be mysqli

最佳答案

在连接方法中,您没有将 mysqli 对象分配给实例变量。

__destruct中,$con未定义/NULL,这解释了错误消息。

require_once __DIR__ . '/db_config.php';

class DB_CONNECT {
private $conn;
function __construct() {
$this->connect();
}

function __destruct() {
$this->close();
}

function connect() {
$this->conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE)
or die(mysqli_error());
echo "connected succesfully";
}

function close() {
mysqli_close($this->conn);
}
}

关于PHP 析构函数显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29322332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com