假设我有两个 php 类 - 类 Security
和类 Database
安全
class Security {
public function userPermissions() {
//use getData() from Database to obtain information
}
}
数据库
class Database {
public function getData() {
// some code
}
}
安全类需要使用数据库类获取数据,有很多方法可以实现这一点,但我不确定最佳实践。
创建两者的实例是否更好;
$db = new Database;
$sec = new Security($db);
然后在安全类中使用构造函数将数据库实例传递给它?
或者您会在安全类的 __constructor 方法中创建一个新实例吗?
如果有任何最佳实践,我将不胜感激。
最佳答案
Create an instance of both and then in the Security class use a constructor to pass the instance of the db to it
您描述的方法称为 Dependency injection从架构的角度来看,它通常是更适合您的案例的解决方案。
关于php - 在一个类中引用其他类 - php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26562264/