2

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

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

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();
    }

Comments

1

Try this:

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

Comments

0

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.