Problem
In PHP, I have a parent/child class and am using dependency container to load them. I am trying to use the same database connection on all of them without duplicating the object.
I used $this->_db
to pull data from the database in a child class method (and my class stores that in the property $this->_db->result
). I then went into the parent class and print_r($this->_db->result)
and it worked. That leads me to believe that I am passing the database object and not duplicating it (maybe?).
However, would still be nice if someone could tell me why my code would not be considered OOP, as someone had commented that it was not OOP. Can someone who understands this stuff better than me please have a look and let me know if I’m doing it right and if not, what I need to change in my code?
<?php
include('mysqliClass.php');
$db = new mysqliObject();
depCon::$_database = $db;
$myObject = depCon::createNewObject();
class depCon {
public static $_database;
public static function createNewObject() {
$newObject = new myChild();
$newObject->setDatabase(self::$_database);
return $newObject;
}
}
class myParent {
private $_db;
public function __construct() {
}
public function setDatabase($databaseConnection) {
$this->_db = $databaseConnection;
}
}
class myChild extends myParent {
private $_db;
public function __construct() {
parent::__construct();
}
public function setDatabase($databaseConnection) {
$this->_db = $databaseConnection;
parent::setDatabase($this->_db);
}
}
?>
Solution
Don’t use a private attribute for the database, use a protected one. That way both classes can share the same $_db, and you only need one setDatabase.
As for your code being OO or not, there simply isn’t enough code here to make the claim one way or the other.
Why should an object know about a database (in an OOP sense)? I’m definitely no friend of the Singleton pattern, but a database is in most projects a valid use case.
Your code might not be OO but Service Oriented as you are injecting the database(-service) to your objects.