Sharing objects between PHP classes

2019-01-28 06:21发布

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;
}

Would passing the objects in, eg.

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

Be the way to go?

标签: php oop
5条回答
ゆ 、 Hurt°
2楼-- · 2019-01-28 06:36

The way to go would be singletons if they have a single instance. If not, the only way is to pass them during initialization (say: in the constructor).

查看更多
▲ chillily
3楼-- · 2019-01-28 06:36

You could also use objects that have been loaded in session or in cache (APC,memcached) before. Personnaly i think singleton is the best way to go there (especially for database class)

查看更多
放荡不羁爱自由
4楼-- · 2019-01-28 06:38

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).

查看更多
我想做一个坏孩纸
5楼-- · 2019-01-28 06:38

Yes, that's pretty much the way you want to do. If a class has external requirements, don't create them inside the class, but require them as arguments in the constructor.

查看更多
干净又极端
6楼-- · 2019-01-28 06:45

That would be a step in the right direction, but it does seem to me that you do actually want a singleton there, even if not actually constrained in code.

查看更多
登录 后发表回答