I am trying to learn OOP php and as I was developing a login/register system, I noticed that I am calling the Database clase in every function in my Users class.
For example, like this:
<?php
class Users {
public function signUp($username, $email, $password){
$db = new Database;
$dbh = $db->connect();
$sql = "INSERT INTO users (username, email, password) VALUES (?, ?, ?)";
try {
$query = $dbh->prepare($sql);
$query->execute(array($username, $email, $password));
echo 'succ';
} catch (Exception $ex) {
echo $ex->getMessage();
}
}
Basically, without copying the whole file, I have a few functions that work with the database and in every single one of them I have to call these two lines:
$db = new Database;
$dbh = $db->connect();
So I looked up on the internet and found about the spl_autoload_register. It worked perfectly for the most part, however I can't seem to replace the two lines from above like this:
$db = new Database;
$dbh = Database::connect();
as I get another error from my Database class:
Using $this when not in object context in D:\xampp\htdocs\PHP OOP\customSystem\Classes\Class.Database.php on line 24
Line 24 is the return of this function
public function connect(){
return $this->conn;
}
and I am out of ideas of what to do now, but it won't solve my initial problem with calling the Database class in every function, too. So, what do I need to do?