gpt4 book ai didi

php - 将数据库对象从类中的一个方法传递到另一个方法的正确方法是什么

转载 作者:行者123 更新时间:2023-11-29 06:56:26 24 4
gpt4 key购买 nike

我需要帮助来理解将在一个方法中创建的对象(MySQL 连接)传递给同一类中的另一个方法的正确方法。

我正在尝试创建一个数据库类,它使用构造函数和所有其他方法加载连接,使用这个连接来执行它们各自的功能。

在尝试这样做时,我不断收到此错误:

Fatal error: Call to a member function query() on a non-object in /database.php on line 44

我的代码:

class database
{
public $mysqli;

public function __construct($database_server, $database_name, $database_user, $database_pass)
{
$mysqli = new mysqli($database_server,$database_user, $database_pass, $database_name);

if ($mysqli->connect_error)
{
die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);
}
echo "Database connection established successfully.<br>";
return $this->mysqli;

}

public function fetch_data()
{

$query = "select * from payment";
if ($result = $this->mysqli->query($query))
{

// fetch associative array
while ($row = $result->fetch_assoc())
{
printf ("%s (%s)\n", $row["id"], $row["status"]);
}

}

}
}

如有任何帮助,我们将不胜感激。谢谢大家。

最佳答案

public function __construct($database_server, $database_name, $database_user, $database_pass)
{
$mysqli = new mysqli($database_server,$database_user, $database_pass, $database_name);

if ($mysqli->connect_error)
{
die('Connect Error (' . $mysqli->connect_errno . ') '. $mysqli->connect_error);
}
echo "Database connection established successfully.<br>";

// instead of return, just set the local variable to the `mysqli` property.
$this->mysqli = $mysqli;

}

或者

public function __construct($database_server, $database_name, $database_user, $database_pass)
{
$this->mysqli = new mysqli($database_server,$database_user, $database_pass, $database_name);

if ($this->mysqli->connect_error)
{
die('Connect Error (' . $this^>mysqli->connect_errno . ') '. $this->mysqli->connect_error);
}
echo "Database connection established successfully.<br>";
}

public $mysqli; 会更好protected

关于php - 将数据库对象从类中的一个方法传递到另一个方法的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12446521/

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