I was watching an OOP lesson with such code:

class UsersConstroller {

    protected $userService
    protected $logger

    public function __construct {

        UserService $userService,
        Logger $logger


What this class does is pass other class in the constructor, then it will assign them to variable, and they will be used with $this inside the class.

Is it wrong not to pass those classes in the constructor, and instantiate them directly where needed in the class code, like this:

( new Logger )->logMessage("this is a message")

This way, passing a lot of instances of other classes to the class would be avoided.


What is described in the example you provided is called Dependency Injection and is generally considered a good practice.

Instantiating the objects of the class whenever you need them can result in degradation of performance, memory fragmentation and greater memory consupmtion in managed languages (it would take time for garbage collector to release some of those references). Not to mention that you would need to release that memory every time in unmanaged languages, which means there would be a big risk of memory leaks (somewhere you would forget to write delete logger).

As a matter of fact, I can see no valid scenario where something like (new Logger)-> logMessage("this is a message") would be used, apart from the situation where logger would be a local variable, i.e. without any impact on other methods of that class.

In this particular case, though, considering what logger tipically does, there is absolutely no scenario where doing something like this is a good practice. Logger class should be able to handle concurrent writing in the same log file from several threads. If you instantiate a new class each time, this would be very hard to achieve.

  • Thanks for your answer. Wouldn't the injected dependency class still need to be instanciated locally ? Mar 2 '17 at 10:40
  • 1
    That is correct, it would be instatiated locally somewhere, but only once. Imagine that you have ten instances of UsersController class and you use Dependency Injections. Logger class would be instantiated once and just passed on to UsersController class, whereas if it is instantiated locally within UsersController class, it would be instantiated 10 times. Mar 2 '17 at 11:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.