I have two classes, Database and User. In the Database class I have function to connect to the database. I am wanting to be able to have a connection to the database within the User class. This is what I am currently doing in the User Class:
class User {
function __construct()
{
require_once 'database.class.php';
$DBH = new Database();
$DBH->connect();
}
function register_user()
{
$DBH->prepare('INSERT INTO users VALUES (:username, :password, :forename, :surname)');
$DBH->execute(array(':username' => 'administrator', ':password' => '5f4dcc3b5aa765d61d8327deb882cf99', ':forename' => 'Richie', ':surname' => 'Jenkins'));
}
}
I get the following error:
PHP Fatal error: Call to a member
function prepare() on a non-object
You should read about “scope.”
$DBHis only declared locally in__construct().Rectifying this is easy. Simply add
and wherever you have
$DBHchange to$this->DBH. May help to read about$thisand member variables as well.