Sharing objects between PHP classes

前端 未结 5 1718
予麋鹿
予麋鹿 2020-12-21 04:17

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\" obje

相关标签:
5条回答
  • 2020-12-21 04:37

    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.

    0 讨论(0)
  • 2020-12-21 04:39

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

    0 讨论(0)
  • 2020-12-21 04:46

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

    0 讨论(0)
  • 2020-12-21 04:49

    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)

    0 讨论(0)
  • 2020-12-21 04:54

    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.

    0 讨论(0)
提交回复
热议问题