I have this 2 classes:
class EventScripts {
protected $database;
private $test;
public function __construct(Database $database) {
$this->database = $database;
}
public function ScriptA($callTime, $params) {
// Does NOT output the information of the database. It simply does nothing and the code aborts.
var_dump($this->database);
return $params;
}
}
class EventSystem {
protected $database;
protected static $results;
public function __construct(Database $database) {
$this->database = $database;
}
public function handleEvents() {
// outputs the array with information of the database
var_dump($this->database);
$EventScripts = new EventScripts($this->database);
$EventScripts->ScriptA(5, "test");
}
}
I call EventSystem
like this:
try {
$database = new Database("host", "user", "password", "database");
$EventSystem = new EventSystem($database);
} catch (Exception $e) {
echo $e->getMessage();
}
$EventSystem->handleEvents();
Now the var_dump()
in EventSystem
correctly shows me the information of the database that is saved in the protected $database
-variable.
But when I do this exact thing in the ScriptA()
-method, nothing happens and the code aborts. It even doesn't return anything anymore.
Where is my mistake?
Protected members of classes are available to the class and inherited classes of it. Not to entirely different classes.
In you can you can extend both classes from one (perhaps abstract) class that is "with database" and it has that details encapsulated as a protected member.
abstract class DatabaseBased
{
/**
* @var Database
*/
protected $database;
public function __construct(Database $database)
{
$this->setDatabase($database);
}
protected function setDatabase(Database $database)
{
$this->database = $database;
}
}
Here the one class you had problems with:
class EventScripts extends DatabaseBased
{
private $test;
public function ScriptA($callTime, $params)
{
var_dump($this->database);
return $params;
}
}
When you now create the other object, you can inject the database directly:
public function handleEvents() {
// outputs the array with information of the database
$EventScripts = new EventScripts();
$EventScripts->setDatabase($this->database);
$EventScripts->ScriptA(5, "test");
}