Bird
Raised Fist0
PHPprogramming~20 mins

Dependency injection concept in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Dependency Injection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
What is the main benefit of dependency injection?

Consider a PHP class that needs to use a database connection. What is the main benefit of using dependency injection to provide the database connection to the class?

AIt makes the class tightly coupled to a specific database implementation.
BIt allows the class to receive the database connection from outside, making it easier to test and change dependencies.
CIt allows the class to create the database connection internally whenever needed.
DIt forces the class to manage the lifecycle of the database connection.
Attempts:
2 left
💡 Hint

Think about how receiving dependencies from outside helps with testing and flexibility.

❓ component_behavior
intermediate
2:00remaining
What will this PHP code output when using dependency injection?

Given the following PHP code, what will be the output?

PHP
<?php
class Logger {
    public function log($msg) {
        echo "Log: $msg";
    }
}

class User {
    private $logger;
    public function __construct(Logger $logger) {
        $this->logger = $logger;
    }
    public function create() {
        $this->logger->log('User created');
    }
}

$logger = new Logger();
$user = new User($logger);
$user->create();
?>
AFatal error: Uncaught Error: Class 'Logger' not found
BUser created
CLog:
DLog: User created
Attempts:
2 left
💡 Hint

Look at how the logger is passed to the User class and used in the create method.

📝 Syntax
advanced
2:00remaining
Which option correctly injects a dependency in PHP constructor?

Which of the following PHP code snippets correctly injects a dependency into a class constructor?

Aclass Service { public function __construct(Database $db) { $this->db = $db; } }
Bclass Service { public function __construct($db) { $db = $this->db; } }
Cclass Service { function __construct(Database $db) { $this->db == $db; } }
Dclass Service { public function __construct(Database $db) { $db->this = $this; } }
Attempts:
2 left
💡 Hint

Check the assignment direction and parameter typing.

🔧 Debug
advanced
2:00remaining
Why does this dependency injection code cause an error?

Given this PHP code, why does it cause a fatal error?

PHP
<?php
class Mailer {}
class Notification {
    private $mailer;
    public function __construct() {
        $this->mailer = new Mailer();
    }
}

$notification = new Notification(new Mailer());
?>
ANotification constructor does not accept any parameters but is called with one.
BMailer class is not defined before use.
CNotification class tries to inject Mailer but does not assign it.
DMailer class constructor requires parameters but none are given.
Attempts:
2 left
💡 Hint

Look at the constructor signature and how the object is instantiated.

❓ lifecycle
expert
2:00remaining
How does dependency injection affect object lifecycle in PHP?

In PHP, when using dependency injection, which statement best describes how the lifecycle of injected objects is managed?

AInjected objects are always created inside the dependent class and destroyed with it.
BInjected objects must be static to survive beyond the dependent class lifecycle.
CInjected objects are created outside and can be shared or reused independently of the dependent class lifecycle.
DInjected objects are cloned automatically when injected to avoid shared state.
Attempts:
2 left
💡 Hint

Think about who creates the injected object and how that affects its lifetime.

Practice

(1/5)
1. What is the main idea behind dependency injection in PHP?
easy
A. Providing a class with its required objects from outside instead of creating them inside.
B. Writing all code inside one big class for simplicity.
C. Using global variables to share data between classes.
D. Making classes depend on static methods only.

Solution

  1. Step 1: Understand dependency injection meaning

    Dependency injection means giving a class the objects it needs from outside, not creating them inside the class.
  2. Step 2: Compare options with this meaning

    Only Providing a class with its required objects from outside instead of creating them inside. describes this idea correctly. Others describe bad or unrelated practices.
  3. Final Answer:

    Providing a class with its required objects from outside instead of creating them inside. -> Option A
  4. Quick Check:

    Dependency injection = Provide dependencies from outside [OK]
Hint: Dependency injection means passing needed parts from outside [OK]
Common Mistakes:
  • Thinking dependency injection means using global variables
  • Confusing dependency injection with static methods
  • Believing all code should be inside one class
2. Which of the following is the correct syntax to inject a dependency via constructor in PHP?
easy
A. public function __construct(Database $db) { $this->db == $db; }
B. public function __construct() { $this->db = new Database(); }
C. public function __construct(Database $db) { $this->db = $db; }
D. public function __construct(Database $db) { $db = $this->db; }

Solution

  1. Step 1: Identify correct constructor injection syntax

    Constructor injection requires passing the dependency as a parameter and assigning it to a class property.
  2. Step 2: Check each option

    public function __construct(Database $db) { $this->db = $db; } correctly assigns the passed $db to $this->db. public function __construct() { $this->db = new Database(); } creates the dependency inside, not injection. public function __construct(Database $db) { $db = $this->db; } assigns backwards. public function __construct(Database $db) { $this->db == $db; } uses wrong operator '=='.
  3. Final Answer:

    public function __construct(Database $db) { $this->db = $db; } -> Option C
  4. Quick Check:

    Constructor injection = assign parameter to property [OK]
Hint: Assign constructor parameter to property with =, not == [OK]
Common Mistakes:
  • Creating dependency inside constructor instead of injecting
  • Using == instead of = for assignment
  • Assigning property to parameter instead of reverse
3. Given the code below, what will be the output?
class Logger {
  public function log($msg) { echo "Log: $msg"; }
}

class User {
  private $logger;
  public function __construct(Logger $logger) {
    $this->logger = $logger;
  }
  public function create() {
    $this->logger->log('User created');
  }
}

$logger = new Logger();
$user = new User($logger);
$user->create();
medium
A. User created
B. Log: User created
C. Error: Logger not found
D. No output

Solution

  1. Step 1: Understand dependency injection in code

    The User class receives a Logger object via constructor and stores it in $this->logger.
  2. Step 2: Trace method calls

    Calling $user->create() calls $this->logger->log('User created'), which echoes "Log: User created".
  3. Final Answer:

    Log: User created -> Option B
  4. Quick Check:

    Injected Logger logs message correctly [OK]
Hint: Injected objects run their methods as expected [OK]
Common Mistakes:
  • Expecting just 'User created' without 'Log:' prefix
  • Thinking code throws error due to missing Logger
  • Assuming no output without echo
4. Identify the error in this dependency injection example:
class Mailer {
  public function send($msg) { echo "Sending: $msg"; }
}

class Notification {
  private $mailer;
  public function __construct() {
    $this->mailer = $mailer;
  }
  public function notify() {
    $this->mailer->send('Hello');
  }
}

$notification = new Notification();
$notification->notify();
medium
A. The notify method should be static.
B. The send method is missing a return statement.
C. The Mailer class is not instantiated anywhere.
D. The constructor does not accept Mailer as a parameter to inject.

Solution

  1. Step 1: Check constructor parameters

    The constructor has no parameters but tries to assign $mailer which is undefined inside it.
  2. Step 2: Identify missing injection

    Mailer object should be passed as a parameter to constructor and assigned to $this->mailer.
  3. Final Answer:

    The constructor does not accept Mailer as a parameter to inject. -> Option D
  4. Quick Check:

    Constructor missing dependency parameter [OK]
Hint: Constructor must accept dependency parameter to inject it [OK]
Common Mistakes:
  • Forgetting to pass dependency to constructor
  • Trying to assign undefined variable inside constructor
  • Thinking notify must be static
5. You want to make a ReportGenerator class that depends on a DataFetcher and a Logger. Which is the best way to apply dependency injection here?
hard
A. Pass both DataFetcher and Logger as constructor parameters and assign them to properties.
B. Create new DataFetcher and Logger objects inside ReportGenerator methods.
C. Use global variables for DataFetcher and Logger inside ReportGenerator.
D. Make ReportGenerator extend DataFetcher and Logger classes.

Solution

  1. Step 1: Understand multiple dependency injection

    When a class needs multiple dependencies, best practice is to pass them all via constructor parameters.
  2. Step 2: Evaluate options

    Pass both DataFetcher and Logger as constructor parameters and assign them to properties. correctly injects both dependencies. Create new DataFetcher and Logger objects inside ReportGenerator methods. creates dependencies inside, breaking injection. Use global variables for DataFetcher and Logger inside ReportGenerator. uses globals, which is bad practice. Make ReportGenerator extend DataFetcher and Logger classes. tries multiple inheritance which PHP does not support.
  3. Final Answer:

    Pass both DataFetcher and Logger as constructor parameters and assign them to properties. -> Option A
  4. Quick Check:

    Inject all dependencies via constructor [OK]
Hint: Inject all needed parts via constructor parameters [OK]
Common Mistakes:
  • Creating dependencies inside methods instead of injecting
  • Using global variables instead of injection
  • Trying to extend multiple classes in PHP
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard