php - 在一个类中引用其他类 - php

标签 php class oop methods

假设我有两个 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/

相关文章:

javascript - OOP Javascript,为什么这个对象不能按预期工作?

php - 有没有办法在使用php检索它后使用存储在mysql中的PHP代码?

PHP PDO fetchAll() 在 bool 上

php - 在站点级别定义 cakephp inputDefaults 的方法

c++ - Boost 突然进入我的命名空间,声称缺少函数的错误

python - 在Python中访问类中的类成员的最佳方法

php - mysqli_fetch_assoc()期望参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

c# - Parent - C# 中的 CChild 管理

java - 将 JPanel 添加到不同类中的另一个 JPanel

html - 如何在 html/css 中并排放置但低于另一个