What are the differences between vererbung and Abhängigkeit in PHP classes?
In PHP classes, "Vererbung" refers to inheritance, where a child class can inherit properties and methods from a parent class. On the other hand, "Abhängigkeit" refers to dependency, where a class relies on another class or external code to function properly. Inheritance promotes code reusability and allows for creating a hierarchy of classes, while dependency injection helps in decoupling classes and making them more testable and maintainable.
// Example of inheritance (Vererbung)
class ParentClass {
protected $property;
public function __construct($property) {
$this->property = $property;
}
}
class ChildClass extends ParentClass {
public function getProperty() {
return $this->property;
}
}
// Example of dependency injection (Abhängigkeit)
class Dependency {
public function doSomething() {
return 'Doing something';
}
}
class MyClass {
private $dependency;
public function __construct(Dependency $dependency) {
$this->dependency = $dependency;
}
public function useDependency() {
return $this->dependency->doSomething();
}
}
$dependency = new Dependency();
$myClass = new MyClass($dependency);
echo $myClass->useDependency();