我想在其他函数中调用$con
变量。这个变量包含我的数据库连接所以一些查询在我的其他函数中运行所以我需要在其他函数中调用这个$con
变量。我是新的PhP OOP所以也许我的概念不好。但请建议加上给我解决方案。
PHP
Class CORE
{
public function connect_database()
{
$connection=mysqli_connect(host,user,"1234");
$con = mysqli_select_db($connection,database);
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}
public function show_name()
{
$user = base64_decode($_SESSION['admin']);
$query = mysqli_query($con,"SELECT full_name FROM admin_user WHERE user='".$user."'");
while($row = mysqli_fetch_array($query))
{
echo $row['full_name'];
}
}
}
答案 0 :(得分:0)
稍微改变你的课程:
Class CORE {
protected $con;
public $error;
public function get_con(){
return $this->con;
}
public function connect_database(){
connection=mysqli_connect(host,user,"1234");
$this->con = mysqli_select_db($connection,database);
if (mysqli_connect_errno($this->con)){
$this->error = mysqli_connect_error();
}
}
public function show_name(){
$user = base64_decode($_SESSION['admin']);
$query = mysqli_query($this->con,"SELECT full_name FROM admin_user WHERE
user='".$user."'");
while($row = mysqli_fetch_array($query)) {echo $row['full_name'];}
}
}
现在创建一个类的实例来检查$con
和$error
:
$test = new CORE();
echo $test->get_con();
echo $test->error;
如果$con
没有错误(并且$error
没有显示错误),请通过$this->con