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?
Think about how receiving dependencies from outside helps with testing and flexibility.
Dependency injection means giving a class the objects it needs instead of creating them inside. This makes the class easier to test and change because it does not depend on specific implementations.
Given the following PHP code, what will be the output?
<?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(); ?>
Look at how the logger is passed to the User class and used in the create method.
The User class receives a Logger instance via its constructor (dependency injection). When create() is called, it calls the log method on the Logger, which prints "Log: User created".
Which of the following PHP code snippets correctly injects a dependency into a class constructor?
Check the assignment direction and parameter typing.
Option A correctly types the parameter and assigns it to the class property. Option A reverses assignment. Option A uses '==' instead of '='. Option A tries to assign to the parameter object incorrectly.
Given this PHP code, why does it cause a fatal error?
<?php class Mailer {} class Notification { private $mailer; public function __construct() { $this->mailer = new Mailer(); } } $notification = new Notification(new Mailer()); ?>
Look at the constructor signature and how the object is instantiated.
The Notification constructor does not accept any parameters, but the code tries to pass a Mailer object when creating Notification, causing a fatal error.
In PHP, when using dependency injection, which statement best describes how the lifecycle of injected objects is managed?
Think about who creates the injected object and how that affects its lifetime.
Dependency injection means the dependent class receives objects created elsewhere. This allows sharing or reusing those objects independently of the dependent class lifecycle.