When should one use inheritance in PHP and when should one use Dependency Injection?
Inheritance in PHP should be used when there is an "is-a" relationship between classes, where one class is a specialized version of another. Dependency Injection should be used when one class requires the functionality of another class, but should not be tightly coupled to it. It allows for better flexibility, testability, and maintainability of code.
// Using Inheritance
class Animal {
public function eat() {
echo "Animal is eating";
}
}
class Dog extends Animal {
public function bark() {
echo "Dog is barking";
}
}
// Using Dependency Injection
class Logger {
public function log($message) {
echo $message;
}
}
class User {
private $logger;
public function __construct(Logger $logger) {
$this->logger = $logger;
}
public function createUser() {
$this->logger->log("User created");
}
}
$logger = new Logger();
$user = new User($logger);
$user->createUser();
Related Questions
- Are there any best practices to keep in mind when replacing characters in a string using PHP?
- In what ways can referencing incorrect directories or versions in the httpd.conf file impact the performance of an Apache server running PHP?
- What are some best practices for handling MySQL queries in PHP to avoid errors like "Fehler in query1"?