在PHP类之间共享对象 [英] Sharing objects between PHP classes

查看:58
本文介绍了在PHP类之间共享对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在其他类之间共享对象的最佳方法是什么?

What is the best way to share objects between other classes?

例如;具有商品"和用户"对象所需功能的数据库"对象.

For example; a "database" object with functions that are required by the "article" and "user" objects.

我不想使用全局变量(包括单例)或在每个类中创建对象的新实例,例如

I don't want to use globals (that includes singletons) or create a new instance of the object in each class, such as

function __construct() {
    $this->database = new database;
    $this->cache = new cache;
}

例如,将对象传入.

class test{
    function __construct( $obj ) {
        $this->obj = $obj;
    }
}
$database = new database;
$test = new test( $database );

要走吗?

推荐答案

是.将对象传递给构造函数或传递给setter的方法是最好的方法.这种模式称为依赖注入.它的另一个好处是使您的代码更易于测试(使用存根或模拟).

Yes. Passing the objects to the constructor - or to a setter - is the best way to go. This pattern is known as dependency injection. It has the added benefit that it makes your code easier to test (using stubs or mocks).

这篇关于在PHP类之间共享对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆