What is the best way to share a class instance between two inherited classes?
// Let's create a main class that hold common methods and connects to the database
class MyApp {
public $DB;
function __construct () {
// Connect to the database here
$this->DB = new Database();
}
}
// This will hold methods specific to the user management
class Users extends MyApp {
function __construct() {
parent::__construct();
}
}
// This will hold methods specific for fetching news articles
class News extends MyApp {
function __construct() {
parent::__construct();
}
}
Now, in my application I have page that displays both Users and News on the same page. So I do something like this:
// Instantiate the users class (this will connect to the db)
$users = new Users();
// Instantiate the news calls (PROBLEM! This will create a new db connection instead of re-using the previous one)
$news = new News();
I can keep the DB instance separate and then pass it in. Something like this:
$db = new Database();
$users = new Users($db);
$news = new News($db);
But now I'm passing this stupid $db variable everywhere -- which feels messy and error-prone.
Is there a better way to structure this? The ideal solution would look something like this:
// Instantiate a global class which will connect the DB once
$App = new MyApp();
// Reference sub-classes which all share the parent class variables.
// Unfortunately PHP doesn't seem to have sub-class support :(
$App->Users->someMethod();
$App->News->someMethod();