我在 connections.php 中声明了mysqli连接。我声明 $ this->连接而不是 $ connect ,因为我想将一个文件中的每个函数分开。
<?php
$this->connection = mysqli_connect("localhost","root","","itdforum");
if(mysqli_connect_errno){
echo "Failed to connect to MYSQL: " . mysqli_connect_error();
}
?>
我试图在其他功能中使用 $ this-connection
<?php
include("connections.php");
function getSome(){
$get_some = "SELECT * FROM table"
$run_some = mysqli_query($this->connection, $get_some);
}
?>
但错误显示如下
Using $this when not in object context in localhost\connections.php
有谁知道如何修复它?或者我只是将所有功能添加到一个php文件中?谢谢。
答案 0 :(得分:1)
听起来你想要一堂课:
class Thing {
function __construct(){
$this->connection = mysqli_connect(...)
if(mysqli_connect_errno){
echo "Failed to connect to MYSQL: " . mysqli_connect_error();
}
}
function getSome(){
$get_some = "SELECT * FROM table"
$run_some = mysqli_query($this->connection, $get_some);
}
}
使用它:
include('Thing.php');
$thing = new Thing();
$thing->getSome();