php变量没有存储

时间:2012-10-23 18:03:36

标签: php mysql mysqli

我正在尝试使用php创建一个db类,它将主机ect作为变量。我不能得到初始值,我不知道为什么。当我在顶部初始化它们,我将它们设置为公共它工作正常,但当我尝试在构造函数中初始化它时它不起作用。

    class Database {

    public $dbHost;
    public $dbUser;
    public $dbPass;
    public $dbName;

    public $db;

    public function __construct($Host, $User, $Pass, $Name){ 
        $dbHost = $Host;
        $dbUser = $User;
        $dbPass = $Pass;
        $dbName = $Name;
        $this->dbConnect();
    }

    public function dbConnect(){
        echo $dbPass;
        $this->db = new mysqli($this->dbHost, $this->dbUser, $this->dbPass, $this->dbName);

        /* check connection */
        if (mysqli_connect_errno()){
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }else{
            //echo 'connection made';
        }
    }

5 个答案:

答案 0 :(得分:6)

你没有在构造函数中正确初始化它们;尝试:

$this->dbHost = $Host;

您目前正在做的是初始化一个名为$ dbHost的局部变量,其范围只是构造函数本身。

答案 1 :(得分:2)

您必须使用$this来访问类中的实例变量,例如$this->dbHost = $Host;

答案 2 :(得分:2)

改变这个:

public function __construct($Host, $User, $Pass, $Name){ 
        $dbHost = $Host;
        $dbUser = $User;
        $dbPass = $Pass;
        $dbName = $Name;
        $this->dbConnect();
    }

到此:

public function __construct($Host, $User, $Pass, $Name){ 
        $this->dbHost = $Host;
        $this->dbUser = $User;
        $this->dbPass = $Pass;
        $this->dbName = $Name;
        $this->dbConnect();
    }

答案 3 :(得分:1)

试试这个:

public function __construct($Host, $User, $Pass, $Name){ 
        $this->dbHost = $Host;
        $this->dbUser = $User;
        $this->dbPass = $Pass;
        $this->dbName = $Name;
        $this->dbConnect();
    }

答案 4 :(得分:0)

如何使用 this->

public function __construct($Host, $User, $Pass, $Name){ 
    $this->dbHost = $Host;
    $this->dbUser = $User;
    $this->dbPass = $Pass;
    $this->dbName = $Name;
    $this->dbConnect();
}