What are the potential pitfalls of creating dependencies between PHP classes, such as in the example of a Bremse and Auto relationship?
Creating dependencies between PHP classes can lead to tightly coupled code, making it difficult to maintain and test. To solve this issue, it is recommended to use dependency injection, where the dependencies are passed to the class from outside rather than being created within the class itself. This allows for better flexibility, scalability, and testability of the code.
class Bremse {
public function bremsen() {
// Bremsen logic
}
}
class Auto {
private $bremse;
public function __construct(Bremse $bremse) {
$this->bremse = $bremse;
}
public function fahren() {
// Fahrlogik
$this->bremse->bremsen();
}
}
$bremse = new Bremse();
$auto = new Auto($bremse);
$auto->fahren();