我有两个类:
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");
}
}
我这样称呼EventSystem
:
try {
$database = new Database("host", "user", "password", "database");
$EventSystem = new EventSystem($database);
} catch (Exception $e) {
echo $e->getMessage();
}
$EventSystem->handleEvents();
现在EventSystem
中的var_dump()
正确地向我显示了保存在受保护的$database
-变量中的数据库的信息。
但是,当我在ScriptA()
-方法中做这件事时,什么也没发生,代码就中止了。它甚至什么都不回了。
我的错误在哪里?
受保护的类成员可用于该类及其继承类。而不是完全不同的类。
在中,您可以从一个(可能是抽象的)类扩展这两个类,该类"带有数据库",并且它将这些细节封装为受保护的成员。
abstract class DatabaseBased
{
/**
* @var Database
*/
protected $database;
public function __construct(Database $database)
{
$this->setDatabase($database);
}
protected function setDatabase(Database $database)
{
$this->database = $database;
}
}
这里是你遇到问题的一个类:
class EventScripts extends DatabaseBased
{
private $test;
public function ScriptA($callTime, $params)
{
var_dump($this->database);
return $params;
}
}
现在创建另一个对象时,可以直接注入数据库:
public function handleEvents() {
// outputs the array with information of the database
$EventScripts = new EventScripts();
$EventScripts->setDatabase($this->database);
$EventScripts->ScriptA(5, "test");
}