我如何在函数中访问连接变量

时间:2015-07-26 11:47:56

标签: php oop

我想在下面提到班级提及$ 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()

1 个答案:

答案 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;
    }
}