Troy Cosentino
Troy Cosentino

Reputation: 4778

php variables not storing

I am trying to create a db class with php that takes the host ect as variable. I cant get the initialized values to stick and i am not sure why. When i initialize them at the top where i set them to public it works fine, but when i try to initialize them in the constructor it is not working.

    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';
        }
    }

Upvotes: 2

Views: 88

Answers (5)

user1726343
user1726343

Reputation:

Try this:

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

Upvotes: 1

JDischler
JDischler

Reputation: 301

How about using this->

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

Upvotes: 0

Jacek Sokolowski
Jacek Sokolowski

Reputation: 597

Change this:

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

to this:

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

Upvotes: 2

Musa
Musa

Reputation: 97672

You have to use $this to access instance variables inside a class e.g. $this->dbHost = $Host;

Upvotes: 2

andrewsi
andrewsi

Reputation: 10732

You're not initializing them properly in the constructor; try:

$this->dbHost = $Host;

What you're currently doing is initializing a local variable called $dbHost, whose scope is just the constructor function itself.

Upvotes: 6

Related Questions