Let' suppose I have my code organized in classes and each class has its own file:
- main.php, having class Main
- config.php having class Config
- security.php having class Security
- database.php having class Database
Now, Main's constructor will initialize 3 objects, one for each of the other classes, and this way everything will look more or less like a class/subclass. The problem is that now Security might need something (a variable or function) from Config and Database something from Security.
// main.php
// here I include the other files
class Main {
functions __constructor() {
$this->Config = new Config();
$this->Security = new Security();
$this->Database = new Database();
}
}
// config.php
class Config {
public $MyPassword = '123456';
public $LogFile = 'logs.txt';
// other variables and functions
}
// security.php
class Security {
functions __constructor() {
// NOW, HERE I NEED Config->Password
}
function log_error($error) {
// HERE I NEED Config->LogFile
}
}
// database.php
class Database {
functions __constructor() {
// Trying to connect to the database
if (failed) {
// HERE I NEED TO CALL Security->log_error('Connection failed');
}
}
}
So, how do I share those functions and variables between these nested classes inside Main? Of course, I could send those variables as arguments to the constructors but what happens when we need like 5 or 10 of them? I could send the entire object Config to Security and Security to Database,
// main.php
// here I include the other files
class Main {
functions __constructor() {
$this->Config = new Config();
$this->Security = new Security($this->Config);
$this->Database = new Database($this->Security);
}
}
but is that reliable? Can I send only the reference (like a pointer, in C++)? Maybe I can send the hole Main object's reference as an argument in the constructor, and this way make everything available for everything.
// main.php
// here I include the other files
class Main {
functions __constructor() {
$this->Config = new Config();
$this->Security = new Security(&$this);
$this->Database = new Database(&$this);
}
}
I don't even know if this is possible. What do you think? Are there any more conventional ways?