When extending a class in PHP, what are the considerations for using inheritance versus interfaces for better code organization?
When extending a class in PHP, the choice between using inheritance and interfaces depends on the specific requirements of the code organization. Inheritance is useful when there is a clear "is-a" relationship between the classes, where the child class is a specialized version of the parent class. Interfaces, on the other hand, are beneficial when multiple classes need to implement the same set of methods but may not have a common parent class. Consider using inheritance for code reuse and defining a common interface for implementing specific behaviors.
// Example using inheritance
class Animal {
public function eat() {
echo "Animal is eating";
}
}
class Dog extends Animal {
public function bark() {
echo "Dog is barking";
}
}
// Example using interfaces
interface Printable {
public function print();
}
class Document implements Printable {
public function print() {
echo "Document is being printed";
}
}
class Invoice implements Printable {
public function print() {
echo "Invoice is being printed";
}
}