【发布时间】:2013-11-14 13:04:07
【问题描述】:
假设我将代码组织在类中,并且每个类都有自己的文件:
- main.php,具有类 Main
- config.php 具有类 Config
- security.php 具有类 Security
- database.php 具有类 Database
现在,Main 的构造函数将初始化 3 个对象,每个对象一个用于其他类,这样一来,一切都会或多或少像一个类/子类。问题是现在 Security 可能需要来自 Config 的东西(变量或函数)和 Database 来自 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');
}
}
}
那么,我如何在 Main 内的这些嵌套类之间共享这些函数和变量?当然,我可以将这些变量作为参数发送给构造函数,但是当我们需要 5 或 10 个变量时会发生什么?我可以将整个对象 Config 发送到 Security 并将 Security 发送到 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);
}
}
但这可靠吗?我可以只发送引用(如 C++ 中的指针)吗?也许我可以将洞 Main 对象的引用作为构造函数中的参数发送,这样就可以使所有内容都可用。
// 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。
-
数据库需要安全和安全需要配置。如果Security继承了Config,Database继承了Security,那么Database也继承了Config吗?如果安全需要数据库怎么办?
-
是的,它也继承了配置:)
-
1) 我想您很快就会意识到,但是您的示例中有一些语法错误:
functions __constructor()应该是function __construct()。 2)这就是所谓的“依赖注入”;您的所有建议似乎在很大程度上都是合理的。 3) 您无需担心传递指针或对象引用,因为这就是对象的自然行为方式(具体而言,$foo =& $bar使$foo和$bar成为同一个变量;但变量只“指向” at" 无论如何都是一个对象,所以$foo = $bar使两个变量指向同一个对象)。
标签: php class nested share members