Junior — Middle
How can the concept of polymorphism be implemented in object-oriented programming?
sobes.tech AI
Answer from AI
Polymorphism in object-oriented programming allows objects of different classes to respond to the same messages (method calls) in different ways. In PHP, this is achieved through inheritance and method overriding.
Main ways to implement polymorphism:
- Inheritance and method overriding: a base class declares a method, and derived classes implement it in their own way.
- Interfaces: different classes implement the same interface with the same methods but with different logic.
Example:
interface Logger {
public function log(string $message);
}
class FileLogger implements Logger {
public function log(string $message) {
// Write to file
echo "Writing to file: $message";
}
}
class DatabaseLogger implements Logger {
public function log(string $message) {
// Write to database
echo "Writing to DB: $message";
}
}
function writeLog(Logger $logger, string $msg) {
$logger->log($msg);
}
writeLog(new FileLogger(), "Test");
writeLog(new DatabaseLogger(), "Test");
Here, the writeLog function works with an object of type Logger, without knowing the specific implementation, which is polymorphism.