让我们假设我安排在班我的代码和每个类都有自己的文件:PHP - 从嵌套类访问父类成员
- main.php,上课主要
- 的config.php具有类配置
- security.php具有类SECURI TY
- database.php中上课数据库
现在,主要的构造函数将初始化3个对象,每个对应一个其他类的,而这一切的方式看起来会比较或不像一个类/子类。问题是,现在安全可能需要一些东西(变量或功能)从配置和数据库东西来自安全。
// 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');
}
}
}
那么,如何共享里面主要这些嵌套类之间的函数和变量?当然,我可以将这些变量作为参数发送给构造函数,但是当我们需要5或10个变量时会发生什么?我可以在整个对象发送配置到安全和安全到数据库,
// 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);
}
}
而且是可靠的?我可以只发送参考文件(如C++中的指针)吗?也许我可以在构造函数中将这个对象的引用作为参数发送出去,这样就可以让所有东西都可用。
// 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);
}
}
我甚至不知道这是否可能。 你觉得呢?有没有更多的传统方式?
配置可能是一个静态类。或者,你的类可以继承基类Config。 –
数据库需要安全和安全需要配置。如果安全性继承Config和数据库继承安全性,数据库是否继承Config?如果安全需要数据库呢? – ali
是的,它确实继承了配置:) –