Sharing objects between PHP classes

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

For instance; A database object with the functions required by the article and user objects.

I do not want to use global variables (including singlets) or create a new instance of an object in each class, for example

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

Would miss objects, for example.

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

Will you go?

+4
source share
5 answers

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

+6
source

Yes, it is almost the way you want. If the class has external requirements, do not create them inside the class, but require them as arguments in the constructor.

+1
source

The path to travel will be solitary, if they have one copy. If not, the only way is to pass them during initialization (for example: in the constructor).

0
source

This will be a step in the right direction, but it seems to me that what you are doing really want a singleton there, even if in fact it is not limited by code.

0
source

You can also use objects that were previously loaded into the session or into the cache (APC, memcached). Personnaly I think singleton is the best way to go there (especially for the database class)

0
source