-1

I have a difficulty understanding this,

The values for $dbhost $dbuser; $dbpass; $dbname; $dbconnection; are already declared directly under the class name, so it is expected to be accessed in the entire class.

   class Database {

        protected  $dbhost;
        protected  $dbuser;
        protected  $dbpass;
        protected  $dbname;
        protected  $dbconnection;

    }

In constructor(__construct), the values were initialized using the $this->[variablename], hence:

$dbhost = $this->dbhost = 'localhost';
$dbuser = $this->dbuser = 'root';
$dbpass = $this->dbpass = '';
$dbname = $this->dbname = 'forms_db';   
$dbconnection = $this->dbconnection = (mysql_connect($dbhost, $dbuser, $dbpass));       

the new values are expected to be stored in the class variables as their values have been changed

however, whenever I access the values using another method, I get an Undefined variable errors.

here is the rest of my code:

<?php

class Database {

    protected  $dbhost;
    protected  $dbuser;
    protected  $dbpass;
    protected  $dbname;
    protected  $dbconnection;




    function __construct() {

        $dbhost = $this->dbhost = 'localhost';
        $dbuser = $this->dbuser = 'root';
        $dbpass = $this->dbpass = '';
        $dbname = $this->dbname = 'forms_db';   
        $dbconnection = $this->dbconnection = (mysql_connect($dbhost, $dbuser, $dbpass));       

         if(!$dbconnection) die("Could not connect to database. " . mysql_error());

        return ($dbconnection);
    }

function testing(){


                echo $dbhost;
                echo $dbuser;
                echo $dbpass;
                echo $dbname;
                echo $dbconnection;         


        }

}

$data = new Database();

$data->testing();
Devz
  • 9
  • 2
    `echo $this->dbhost`, etc. Also, constructors don't return anything. *Also* also, **read this** - [Why shouldn't I use mysql_* functions in PHP?](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – Phil Feb 12 '14 at 02:36

2 Answers2

1

In your testing method you're not echoing the properties.

Change:

echo $dbuser;

To:

echo $this->dbuser;

Do this for all properties you're trying to access.

Nathan Dawson
  • 18,138
  • 3
  • 52
  • 58
0

testing function change into

function testing(){


                echo $this->dbhost;
                echo $this->dbuser;
                echo $this->dbpass;
                echo $this->dbname;
                echo $this->dbconnection;
        }

}

Because $dbhost is undefined in function testing.