0
0
PHPprogramming~5 mins

Dependency injection concept in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is Dependency Injection in simple terms?
Dependency Injection means giving an object what it needs instead of making it create those things itself. It helps keep code clean and easy to change.
Click to reveal answer
beginner
Why is Dependency Injection useful?
It makes code easier to test, change, and reuse because parts don’t depend tightly on each other. You can swap parts without changing the whole system.
Click to reveal answer
intermediate
In PHP, what is a common way to implement Dependency Injection?
You pass the needed objects as parameters to a class constructor or method instead of creating them inside the class.
Click to reveal answer
intermediate
What is the difference between Dependency Injection and Service Locator?
Dependency Injection gives dependencies directly to a class, while Service Locator asks a central place to get dependencies. DI is clearer and easier to test.
Click to reveal answer
beginner
Show a simple PHP example of Dependency Injection using constructor injection.
class Logger {
    public function log($msg) {
        echo $msg . "\n";
    }
}

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();
Click to reveal answer
What does Dependency Injection help to achieve in code?
ALoose coupling between components
BHard coding dependencies inside classes
CMaking code run faster
DAvoiding use of objects
Which of these is a common way to inject dependencies in PHP?
AUsing global variables
BPassing dependencies via constructor
CCreating dependencies inside methods
DUsing static methods only
What is NOT a benefit of Dependency Injection?
ATighter coupling
BEasier testing
CBetter code reuse
DSimpler maintenance
In Dependency Injection, who is responsible for creating the dependencies?
AThe operating system
BThe dependent class itself
CThe PHP interpreter
DThe dependency injection container or caller
Which pattern is considered clearer and easier to test?
AService Locator
BSingleton
CDependency Injection
DFactory
Explain Dependency Injection and why it is helpful in PHP programming.
Think about how objects get what they need without creating it themselves.
You got /3 concepts.
    Describe how you would implement Dependency Injection in a PHP class with an example.
    Focus on how dependencies are passed in and used inside the class.
    You got /3 concepts.