dongyumiao5210 2014-12-29 20:53
浏览 90
已采纳

访问类php内部定义的公共变量

I am new to php and what I am trying to do is get $conn variable outside of the class. I included this file from another file and tried to get the variable using $dbConfig->conn but it returns nothing.

This is the notice I got on the another page. Notice: Undefined variable: dbConfig in C:\xampp\htdocs\Chat\login.php on line 8

<?php 
class dbConfig {
public $host;
public $username;
public $password;
public $dab;
public $conn;

public function dbConnect() {
$conn = mysqli_connect($this->host,$this->username,$this->password);

if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
else{
    echo "Connected successfully to server";
}

$db_selected = mysqli_select_db($conn, $this->dab);

if (!$db_selected) {
    // if the given database doesn't exists
    // creates new database with that name
    $db_sql = 'CREATE DATABASE chatapp';

    // verify the database is created
    if (mysqli_query($conn, $db_sql)){
        echo "Database chatapp already exists or created successfully
";
    } else {
        echo 'Error creating database: ' . mysqli_error() . "
";
    }
}

// creating tables
$table_sql = "CREATE TABLE IF NOT EXISTS users (".
        "uid INT PRIMARY KEY AUTO_INCREMENT,".
        "username VARCHAR(30) UNIQUE,".
        "password VARCHAR(50),".
        "name VARCHAR(100),".
        "email VARCHAR(70) UNIQUE); ";

// verify the table is created
    if (mysqli_query($conn, $table_sql)) {
        echo "Table: users already exists or created successfully
";
    } else {
        echo 'Error creating table: ' . mysqli_error($table_sql) . "
";
    }
}
}

$obj = new dbConfig();

$obj->host = 'localhost';
$obj->username = 'root';
$obj->password = '';
$obj->dab = 'chatapp';
$obj->dbConnect();
  • 写回答

2条回答 默认 最新

  • dqqy64515 2014-12-29 20:58
    关注

    The problem is how you're referencing the class variable inside your methods. Look:

    public function dbConnect() {
        $conn = mysqli_connect($this->host,$this->username,$this->password);
        ...
    

    Here you're creating a local variable (scope restricted to the current method, only) called $conn. Because you're working with an instance of the class, you need to access your class members using $this:

    $this->conn = mysqli_connect(...);
    

    Take a look at the docs for further info.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.