I'm starting to learn how to use OOP within PHP and so far I want to create a Database class that looks like this:
class Database{
//Database connection variables
private $DBHost = "localhost";
private $DBUser = "username";
private $DBPass = "password";
private $DBName = "database3";
public $DBCon;
public function __construct(){
$this->DBCon = new mysqli($this->DBHost,$this->DBUser,$this->DBPass,$this->DBName);
}
public function con(){
return $this->DBCon;
}
public function __destruct(){
$this->DBCon->close();
}
}
And I'm trying to interact with that class from another one called Application:
include('Database.php');
class Application{
public $DB;
public function __construct() {
$DB = new Database();
}
public function InsertName($Username){
var_dump($this->DB->con());
if($this->DB->con()->query("INSERT INTO Test (name) VALUES ($Username);") === TRUE){
echo "Okay";
}else{
echo "Error";
}
}
}
But I get the error Call to a member function con() on a non-object
As a side note, is this an appropriate way to interact with a database in OOP?
Inside the Application class constructor, $DB
is being assigned new Database()
.
This variable is considered a local variable in this case with its scope being the constructor function itself.
To properly assign the new database object to the public $DB
property, you will need to access it via the object's $this
reference.
public function __construct() { $this->DB = new Database(); }
This way you will be able to access the proper assigned public property throughout your remaining class methods.