大家好,我是 OOP 的新手,我想运行两个需要相同连接的函数。我正在努力以一种允许两个函数使用它的方式声明 $mysqli 变量。我宁愿只使用那个,因为我稍后会添加更多功能。非常感谢任何帮助。
我收到的错误信息是;
注意: undefined variable :C:\Users\PC\Documents\XAMPP\htdocs\test.php 第13行的mysqli
<?php
class OOP
{
function __construct(){
$mysqli = new mysqli('localhost', 'c3337015', 'c3337015', 'iitb');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
function getMember(){
$stmt = $mysqli->prepare("SELECT First_Name FROM forum members");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($First_Name);
while ($row = $stmt->fetch()) {
echo $First_Name;
}
}
function getForum(){
$stmt = $mysqli->prepare("SELECT ForumTitle FROM forum");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($ForumTitle);
while ($row = $stmt->fetch()) {
echo $ForumTitle;
}
}
}
最佳答案
您在构造函数中声明了 $mysqli
,但它不是类变量。您可以简单地将其添加为类变量:
class OOP {
private $mysqli;
...
然后任何时候你想访问变量,用$this->mysqli
替换$mysqli
。
关于php - PHP 中的 OOP - "__construct"连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22413042/