我想在下面提到班级提及$ conn。
conn_file.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if($conn->connect_error)
{
die("Connection Failed :".$conn->connect_error);
}
?>
class.function.php
<?php
include_once 'conn_file.php';
class all_function
{
public function something()
{
$data = $conn->real_escape_string("data");
return $data;
}
}
?>
上面给出了以下错误: 注意:未定义的变量:第7行的class.function.php中的conn
致命错误:在第7行的class.function.php中的非对象上调用成员函数real_escape_string()
答案 0 :(得分:1)
我建议您使用class
进行连接。例如:
在conn_file.php
class DbConfig{
public static $servername = "localhost";
public static $username = "root";
public static $password = "";
public static function getCon(){
$conn = new mysqli(self::$servername, self::$username, self::$password);
if($conn->connect_error){
die("Connection Failed :".$conn->connect_error);
}
return $conn;
}
}
在class.function.php
include_once 'conn_file.php';
class all_function
{
public function something()
{
$conn = DbConfig::getCon();
$data = $conn->real_escape_string("data");
return $data;
}
}