Which of the following code snippets correctly implements this?
hard📝 Application Q8 of 15
PHP - Inheritance and Polymorphism
You want to create an abstract class Logger with an abstract method log() that accepts a string message. Then create a subclass FileLogger that writes the message to a file. Which of the following code snippets correctly implements this?
Aabstract class Logger {
public function log(string $msg) {}
}
class FileLogger extends Logger {
public function log(string $msg) {
file_put_contents('log.txt', $msg.PHP_EOL);
}
}
Babstract class Logger {
abstract public function log(string $msg);
}
class FileLogger extends Logger {
public function log(string $msg) {
file_put_contents('log.txt', $msg.PHP_EOL, FILE_APPEND);
}
}
Cclass Logger {
abstract public function log(string $msg);
}
class FileLogger extends Logger {
public function log(string $msg) {
file_put_contents('log.txt', $msg.PHP_EOL, FILE_APPEND);
}
}
Dabstract class Logger {
abstract public function log();
}
class FileLogger extends Logger {
public function log(string $msg) {
file_put_contents('log.txt', $msg.PHP_EOL, FILE_APPEND);
}
}
Step-by-Step Solution
Solution:
Step 1: Check abstract class and method declaration
Logger is abstract and declares abstract method log() with string parameter.
Step 2: Check subclass implementation
FileLogger extends Logger and implements log(string $msg) correctly, appending message to file.
Step 3: Verify file_put_contents usage
Uses FILE_APPEND flag to add message without overwriting file.
Final Answer:
abstract class Logger with abstract log(string $msg) implemented correctly in FileLogger. -> Option B
Quick Check:
Abstract method with parameter and correct subclass implementation [OK]
Quick Trick:Match method signature exactly when implementing abstract methods [OK]
Common Mistakes:
Not declaring Logger as abstract
Missing parameter in abstract method
Incorrect file_put_contents flags
Trying to declare abstract method in non-abstract class
Master "Inheritance and Polymorphism" in PHP
9 interactive learning modes - each teaches the same concept differently